Axios ES2017 (#4787)

* Added AxiosHeaders class;

* Fixed README.md href;

* Fixed a potential bug with headers normalization;

* Fixed a potential bug with headers normalization;
Refactored accessor building routine;
Refactored default transforms;
Removed `normalizeHeaderName` helper;

* Added `Content-Length` accessor;
Added missed `has` accessor to TS types;

* Added `AxiosTransformStream` class;
Added progress capturing ability for node.js environment;
Added `maxRate` option to limit the data rate in node.js environment;
Refactored event handled by `onUploadProgress` && `onDownloadProgress` listeners in browser environment;
Added progress & data rate tests for the http adapter;
Added response stream aborting test;
Added a manual progress capture test for the browser;
Updated TS types;
Added TS tests;
Refactored request abort logic for the http adapter;
Added ability to abort the response stream;

* Remove `stream/promises` & `timers/promises` modules usage in tests;

* Use `abortcontroller-polyfill`;

* Fixed AxiosTransformStream dead-lock in legacy node versions;
Fixed CancelError emitting in streams;

* Reworked AxiosTransformStream internal logic to optimize memory consumption;
Added throwing an error if the request stream was silently destroying (without error) Refers to #3966;

* Treat the destruction of the request stream as a cancellation of the request;
Fixed tests;

* Emit `progress` event in the next tick;

* Initial refactoring;

* Refactored Mocha tests to use ESM;

* Refactored Karma tests to use rollup preprocessor & ESM;
Replaced grunt with gulp;
Improved dev scripts;
Added Babel for rollup build;

* Added default commonjs package export for Node build;
Added automatic contributors list generator for package.json;

Co-authored-by: Jay <jasonsaayman@gmail.com>
This commit is contained in:
Dmitriy Mozgovoy 2022-06-18 12:19:27 +03:00 committed by GitHub
parent 1db715dd3b
commit bdf493cf8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
125 changed files with 10465 additions and 7294 deletions

14
.eslintrc.cjs Normal file
View File

@ -0,0 +1,14 @@
module.exports = {
"env": {
"browser": true,
"es2017": true,
"node": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"rules": {
}
}

View File

@ -1,151 +0,0 @@
// eslint-disable-next-line strict
module.exports = {
'globals': {
'console': true,
'module': true,
'require': true
},
'env': {
'browser': true,
'node': true
},
'rules': {
/**
* Strict mode
*/
'strict': [2, 'global'], // http://eslint.org/docs/rules/strict
/**
* Variables
*/
'no-shadow': 2, // http://eslint.org/docs/rules/no-shadow
'no-shadow-restricted-names': 2, // http://eslint.org/docs/rules/no-shadow-restricted-names
'no-unused-vars': [2, { // http://eslint.org/docs/rules/no-unused-vars
'vars': 'local',
'args': 'after-used'
}],
'no-use-before-define': 2, // http://eslint.org/docs/rules/no-use-before-define
/**
* Possible errors
*/
'comma-dangle': [2, 'never'], // http://eslint.org/docs/rules/comma-dangle
'no-cond-assign': [2, 'except-parens'], // http://eslint.org/docs/rules/no-cond-assign
'no-console': 1, // http://eslint.org/docs/rules/no-console
'no-debugger': 1, // http://eslint.org/docs/rules/no-debugger
'no-alert': 1, // http://eslint.org/docs/rules/no-alert
'no-constant-condition': 1, // http://eslint.org/docs/rules/no-constant-condition
'no-dupe-keys': 2, // http://eslint.org/docs/rules/no-dupe-keys
'no-duplicate-case': 2, // http://eslint.org/docs/rules/no-duplicate-case
'no-empty': 2, // http://eslint.org/docs/rules/no-empty
'no-ex-assign': 2, // http://eslint.org/docs/rules/no-ex-assign
'no-extra-boolean-cast': 0, // http://eslint.org/docs/rules/no-extra-boolean-cast
'no-extra-semi': 2, // http://eslint.org/docs/rules/no-extra-semi
'no-func-assign': 2, // http://eslint.org/docs/rules/no-func-assign
'no-inner-declarations': 2, // http://eslint.org/docs/rules/no-inner-declarations
'no-invalid-regexp': 2, // http://eslint.org/docs/rules/no-invalid-regexp
'no-irregular-whitespace': 2, // http://eslint.org/docs/rules/no-irregular-whitespace
'no-obj-calls': 2, // http://eslint.org/docs/rules/no-obj-calls
'no-sparse-arrays': 2, // http://eslint.org/docs/rules/no-sparse-arrays
'no-unreachable': 2, // http://eslint.org/docs/rules/no-unreachable
'use-isnan': 2, // http://eslint.org/docs/rules/use-isnan
'block-scoped-var': 2, // http://eslint.org/docs/rules/block-scoped-var
/**
* Best practices
*/
'consistent-return': 0, // http://eslint.org/docs/rules/consistent-return
'curly': [2, 'multi-line'], // http://eslint.org/docs/rules/curly
'default-case': 2, // http://eslint.org/docs/rules/default-case
'dot-notation': [2, { // http://eslint.org/docs/rules/dot-notation
'allowKeywords': true
}],
'eqeqeq': [2, "smart"], // http://eslint.org/docs/rules/eqeqeq
'guard-for-in': 2, // http://eslint.org/docs/rules/guard-for-in
'no-caller': 2, // http://eslint.org/docs/rules/no-caller
'no-else-return': 2, // http://eslint.org/docs/rules/no-else-return
'no-eq-null': 0, // http://eslint.org/docs/rules/no-eq-null
'no-eval': 2, // http://eslint.org/docs/rules/no-eval
'no-extend-native': 2, // http://eslint.org/docs/rules/no-extend-native
'no-extra-bind': 2, // http://eslint.org/docs/rules/no-extra-bind
'no-fallthrough': 2, // http://eslint.org/docs/rules/no-fallthrough
'no-floating-decimal': 2, // http://eslint.org/docs/rules/no-floating-decimal
'no-implied-eval': 2, // http://eslint.org/docs/rules/no-implied-eval
'no-lone-blocks': 2, // http://eslint.org/docs/rules/no-lone-blocks
'no-loop-func': 2, // http://eslint.org/docs/rules/no-loop-func
'no-multi-str': 2, // http://eslint.org/docs/rules/no-multi-str
'no-native-reassign': 2, // http://eslint.org/docs/rules/no-native-reassign
'no-new': 2, // http://eslint.org/docs/rules/no-new
'no-new-func': 2, // http://eslint.org/docs/rules/no-new-func
'no-new-wrappers': 2, // http://eslint.org/docs/rules/no-new-wrappers
'no-octal': 2, // http://eslint.org/docs/rules/no-octal
'no-octal-escape': 2, // http://eslint.org/docs/rules/no-octal-escape
'no-param-reassign': 0, // http://eslint.org/docs/rules/no-param-reassign
'no-proto': 2, // http://eslint.org/docs/rules/no-proto
'no-redeclare': 2, // http://eslint.org/docs/rules/no-redeclare
'no-return-assign': 2, // http://eslint.org/docs/rules/no-return-assign
'no-script-url': 2, // http://eslint.org/docs/rules/no-script-url
'no-self-compare': 2, // http://eslint.org/docs/rules/no-self-compare
'no-sequences': 2, // http://eslint.org/docs/rules/no-sequences
'no-throw-literal': 2, // http://eslint.org/docs/rules/no-throw-literal
'no-with': 2, // http://eslint.org/docs/rules/no-with
'radix': 2, // http://eslint.org/docs/rules/radix
'vars-on-top': 0, // http://eslint.org/docs/rules/vars-on-top
'wrap-iife': [2, 'any'], // http://eslint.org/docs/rules/wrap-iife
'yoda': 2, // http://eslint.org/docs/rules/yoda
/**
* Style
*/
'indent': [2, 2], // http://eslint.org/docs/rules/indent
'brace-style': [2, // http://eslint.org/docs/rules/brace-style
'1tbs', {
'allowSingleLine': true
}],
'quotes': [
2, 'single', 'avoid-escape' // http://eslint.org/docs/rules/quotes
],
'camelcase': [2, { // http://eslint.org/docs/rules/camelcase
'properties': 'never'
}],
'comma-spacing': [2, { // http://eslint.org/docs/rules/comma-spacing
'before': false,
'after': true
}],
'comma-style': [2, 'last'], // http://eslint.org/docs/rules/comma-style
'eol-last': 2, // http://eslint.org/docs/rules/eol-last
'func-names': 0, // http://eslint.org/docs/rules/func-names
'key-spacing': [2, { // http://eslint.org/docs/rules/key-spacing
'beforeColon': false,
'afterColon': true
}],
'new-cap': [2, { // http://eslint.org/docs/rules/new-cap
'newIsCap': true
}],
'no-multiple-empty-lines': [2, { // http://eslint.org/docs/rules/no-multiple-empty-lines
'max': 2
}],
'no-nested-ternary': 2, // http://eslint.org/docs/rules/no-nested-ternary
'no-new-object': 2, // http://eslint.org/docs/rules/no-new-object
'no-spaced-func': 2, // http://eslint.org/docs/rules/no-spaced-func
'no-trailing-spaces': 2, // http://eslint.org/docs/rules/no-trailing-spaces
'no-extra-parens': [2, 'functions'], // http://eslint.org/docs/rules/no-extra-parens
'no-underscore-dangle': 0, // http://eslint.org/docs/rules/no-underscore-dangle
'one-var': [2, 'never'], // http://eslint.org/docs/rules/one-var
'padded-blocks': [2, 'never'], // http://eslint.org/docs/rules/padded-blocks
'semi': [2, 'always'], // http://eslint.org/docs/rules/semi
'semi-spacing': [2, { // http://eslint.org/docs/rules/semi-spacing
'before': false,
'after': true
}],
'keyword-spacing': 2, // http://eslint.org/docs/rules/keyword-spacing
'space-before-blocks': 2, // http://eslint.org/docs/rules/space-before-blocks
'space-before-function-paren': [2, 'never'], // http://eslint.org/docs/rules/space-before-function-paren
'space-infix-ops': 2, // http://eslint.org/docs/rules/space-infix-ops
'spaced-comment': [2, 'always', {// http://eslint.org/docs/rules/spaced-comment
'markers': ['global', 'eslint']
}]
},
'ignorePatterns': ['**/env/data.js']
};

View File

@ -1,101 +0,0 @@
// eslint-disable-next-line strict
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/* <%= pkg.name %> v<%= pkg.version %> | (c) <%= grunt.template.today("yyyy") %> by Matt Zabriskie */\n'
},
clean: {
dist: 'dist/**'
},
package2bower: {
all: {
fields: [
'name',
'description',
'version',
'homepage',
'license',
'keywords'
]
}
},
package2env: {
all: {}
},
eslint: {
target: ['lib/**/*.js']
},
karma: {
options: {
configFile: 'karma.conf.js'
},
single: {
singleRun: true
},
continuous: {
singleRun: false
}
},
mochaTest: {
test: {
src: ['test/unit/**/*.js']
},
options: {
timeout: 30000
}
},
watch: {
build: {
files: ['lib/**/*.js'],
tasks: ['build']
},
test: {
files: ['lib/**/*.js', 'test/**/*.js', '!test/typescript/axios.js', '!test/typescript/out.js'],
tasks: ['test']
}
},
shell: {
rollup: {
command: 'rollup -c -m'
}
}
});
grunt.registerMultiTask('package2bower', 'Sync package.json to bower.json', function() {
var npm = grunt.file.readJSON('package.json');
var bower = grunt.file.readJSON('bower.json');
var fields = this.data.fields || [];
for (var i = 0, l = fields.length; i < l; i++) {
var field = fields[i];
bower[field] = npm[field];
}
grunt.file.write('bower.json', JSON.stringify(bower, null, 2));
});
grunt.registerMultiTask('package2env', 'Sync package.json to env.json', function() {
var npm = grunt.file.readJSON('package.json');
grunt.file.write('./lib/env/data.js', [
'module.exports = ',
JSON.stringify({
version: npm.version
}, null, 2),
';'].join(''));
});
grunt.registerTask('test', 'Run the jasmine and mocha tests', ['eslint', 'mochaTest', 'karma:single']);
grunt.registerTask('build', 'Run rollup and bundle the source', ['clean', 'shell:rollup']);
grunt.registerTask('version', 'Sync version info for a release', ['package2bower', 'package2env']);
};

View File

@ -47,7 +47,7 @@ Promise based HTTP client for the browser and node.js
- [FormData](#formdata)
- [🆕 Automatic serialization](#-automatic-serialization-to-formdata)
- [Files Posting](#files-posting)
- [HTML Form Posting](#html-form-posting-browser)
- [HTML Form Posting](#-html-form-posting-browser)
- [Semver](#semver)
- [Promises](#promises)
- [TypeScript](#typescript)

View File

@ -1,4 +1,4 @@
const {spawn} = require('child_process');
import {spawn} from 'child_process';
const args = process.argv.slice(2);

View File

@ -1,4 +1,4 @@
var people = [
const people = [
{
"name": "Matt Zabriskie",
"github": "mzabriskie",
@ -25,7 +25,7 @@ var people = [
}
];
module.exports = function (req, res) {
export default function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/json'
});

View File

@ -1,5 +1,5 @@
module.exports = function (req, res) {
var data = '';
export default function (req, res) {
let data = '';
req.on('data', function (chunk) {
data += chunk;

View File

@ -1,4 +1,4 @@
module.exports = function (req, res) {
export default function (req, res) {
req.on('data', function (chunk) {
});

View File

@ -1,18 +1,23 @@
var fs = require('fs');
var path = require('path');
var http = require('http');
var argv = require('minimist')(process.argv.slice(2));
var server;
var dirs;
import fs from 'fs';
import path from 'path';
import http from 'http';
import minimist from 'minimist';
import url from "url";
const argv = minimist(process.argv.slice(2));
let server;
let dirs;
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function listDirs(root) {
var files = fs.readdirSync(root);
var dirs = [];
const files = fs.readdirSync(root);
const dirs = [];
for (var i = 0, l = files.length; i < l; i++) {
var file = files[i];
for (let i = 0, l = files.length; i < l; i++) {
const file = files[i];
if (file[0] !== '.') {
var stat = fs.statSync(path.join(root, file));
const stat = fs.statSync(path.join(root, file));
if (stat.isDirectory()) {
dirs.push(file);
}
@ -23,8 +28,8 @@ function listDirs(root) {
}
function getIndexTemplate() {
var links = dirs.map(function (dir) {
var url = '/' + dir;
const links = dirs.map(function (dir) {
const url = '/' + dir;
return '<li onclick="document.location=\'' + url + '\'"><a href="' + url + '">' + url + '</a></li>';
});
@ -74,7 +79,7 @@ function pipeFileToResponse(res, file, type) {
dirs = listDirs(__dirname);
server = http.createServer(function (req, res) {
var url = req.url;
let url = req.url;
// Process axios itself
if (/axios\.min\.js$/.test(url)) {
@ -106,7 +111,7 @@ server = http.createServer(function (req, res) {
}
// Format request /get -> /get/index.html
var parts = url.split('/');
const parts = url.split('/');
if (dirs.indexOf(parts[parts.length - 1]) > -1) {
url += '/index.html';
}
@ -136,5 +141,5 @@ server = http.createServer(function (req, res) {
const PORT = argv.p || 3000;
server.listen(PORT, () => {
console.log(`Examples running on ${PORT}`);
console.log(`Examples running on ${PORT}`);
});

View File

@ -1,5 +1,5 @@
module.exports = function (req, res) {
var data = '';
export default function (req, res) {
let data = '';
req.on('data', function (chunk) {
data += chunk;

87
gulpfile.js Normal file
View File

@ -0,0 +1,87 @@
import gulp from 'gulp';
import fs from 'fs-extra';
import axios from './index.js';
gulp.task('default', async function(){
console.log('hello!');
});
const clear = gulp.task('clear', async function() {
await fs.emptyDir('./dist/')
});
const bower = gulp.task('bower', async function () {
const npm = JSON.parse(await fs.readFile('package.json'));
const bower = JSON.parse(await fs.readFile('bower.json'));
const fields = [
'name',
'description',
'version',
'homepage',
'license',
'keywords'
];
for (let i = 0, l = fields.length; i < l; i++) {
const field = fields[i];
bower[field] = npm[field];
}
await fs.writeFile('bower.json', JSON.stringify(bower, null, 2));
});
async function getContributors(user, repo, maxCount = 1) {
const contributors = (await axios.get(
`https://api.github.com/repos/${encodeURIComponent(user)}/${encodeURIComponent(repo)}/contributors?per_page=${maxCount}`
)).data;
return Promise.all(contributors.map(async (contributor)=> {
return {...contributor, ...(await axios.get(
`https://api.github.com/users/${encodeURIComponent(contributor.login)}`
)).data};
}))
}
const packageJSON = gulp.task('package', async function () {
const CONTRIBUTION_THRESHOLD = 3;
const npm = JSON.parse(await fs.readFile('package.json'));
try {
const contributors = await getContributors('axios', 'axios', 15);
npm.contributors = contributors
.filter(
({type, contributions}) => type.toLowerCase() === 'user' && contributions >= CONTRIBUTION_THRESHOLD
)
.map(({login, name, url}) => `${name || login} (https://github.com/${login})`);
await fs.writeFile('package.json', JSON.stringify(npm, null, 2));
} catch (err) {
if (axios.isAxiosError(err) && err.response && err.response.status === 403) {
throw Error(`GitHub API Error: ${err.response.data && err.response.data.message}`);
}
throw err;
}
});
const env = gulp.task('env', async function () {
var npm = JSON.parse(await fs.readFile('package.json'));
await fs.writeFile('./lib/env/data.js', Object.entries({
VERSION: npm.version
}).map(([key, value]) => {
return `export const ${key} = ${JSON.stringify(value)};`
}).join('\n'));
});
const version = gulp.series('bower', 'env', 'package');
export {
bower,
env,
clear,
version,
packageJSON
}

191
index.d.ts vendored
View File

@ -1,5 +1,6 @@
// TypeScript Version: 4.1
type AxiosHeaders = Record<string, string | string[] | number | boolean>;
type AxiosHeaderValue = string | string[] | number | boolean | null;
type RawAxiosHeaders = Record<string, AxiosHeaderValue>;
type MethodsHeaders = {
[Key in Method as Lowercase<Key>]: AxiosHeaders;
@ -9,18 +10,78 @@ interface CommonHeaders {
common: AxiosHeaders;
}
export type AxiosRequestHeaders = Partial<AxiosHeaders & MethodsHeaders & CommonHeaders>;
type AxiosHeaderMatcher = (this: AxiosHeaders, value: string, name: string, headers: RawAxiosHeaders) => boolean;
export type AxiosResponseHeaders = Record<string, string> & {
type AxiosHeaderSetter = (value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher) => AxiosHeaders;
type AxiosHeaderGetter = ((parser?: RegExp) => RegExpExecArray | null) |
((matcher?: AxiosHeaderMatcher) => AxiosHeaderValue);
type AxiosHeaderTester = (matcher?: AxiosHeaderMatcher) => boolean;
export class AxiosHeaders {
constructor(
headers?: RawAxiosHeaders | AxiosHeaders,
defaultHeaders?: RawAxiosHeaders | AxiosHeaders
);
set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
set(headers?: RawAxiosHeaders | AxiosHeaders, rewrite?: boolean): AxiosHeaders;
get(headerName: string, parser: RegExp): RegExpExecArray | null;
get(headerName: string, matcher?: true | AxiosHeaderMatcher): AxiosHeaderValue;
has(header: string, matcher?: true | AxiosHeaderMatcher): boolean;
delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;
clear(): boolean;
normalize(format: boolean): AxiosHeaders;
toJSON(): RawAxiosHeaders;
static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;
static accessor(header: string | string[]): AxiosHeaders;
setContentType: AxiosHeaderSetter;
getContentType: AxiosHeaderGetter;
hasContentType: AxiosHeaderTester;
setContentLength: AxiosHeaderSetter;
getContentLength: AxiosHeaderGetter;
hasContentLength: AxiosHeaderTester;
setAccept: AxiosHeaderSetter;
getAccept: AxiosHeaderGetter;
hasAccept: AxiosHeaderTester;
setUserAgent: AxiosHeaderSetter;
getUserAgent: AxiosHeaderGetter;
hasUserAgent: AxiosHeaderTester;
setContentEncoding: AxiosHeaderSetter;
getContentEncoding: AxiosHeaderGetter;
hasContentEncoding: AxiosHeaderTester;
}
export type RawAxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>;
export type AxiosRequestHeaders = Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders> & AxiosHeaders;
export type RawAxiosResponseHeaders = Partial<Record<string, string> & {
"set-cookie"?: string[]
};
}>;
export type AxiosResponseHeaders = RawAxiosResponseHeaders & AxiosHeaders;
export interface AxiosRequestTransformer {
(data: any, headers: AxiosRequestHeaders): any;
(this: AxiosRequestConfig, data: any, headers: AxiosRequestHeaders): any;
}
export interface AxiosResponseTransformer {
(data: any, headers?: AxiosResponseHeaders, status?: number): any;
(this: AxiosRequestConfig, data: any, headers: AxiosResponseHeaders, status?: number): any;
}
export interface AxiosAdapter {
@ -43,38 +104,38 @@ export interface AxiosProxyConfig {
}
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'purge' | 'PURGE'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK';
export type ResponseType =
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream';
| 'arraybuffer'
| 'blob'
| 'document'
| 'json'
| 'text'
| 'stream';
export type responseEncoding =
| 'ascii' | 'ASCII'
| 'ansi' | 'ANSI'
| 'binary' | 'BINARY'
| 'base64' | 'BASE64'
| 'base64url' | 'BASE64URL'
| 'hex' | 'HEX'
| 'latin1' | 'LATIN1'
| 'ucs-2' | 'UCS-2'
| 'ucs2' | 'UCS2'
| 'utf-8' | 'UTF-8'
| 'utf8' | 'UTF8'
| 'utf16le' | 'UTF16LE';
export type responseEncoding =
| 'ascii' | 'ASCII'
| 'ansi' | 'ANSI'
| 'binary' | 'BINARY'
| 'base64' | 'BASE64'
| 'base64url' | 'BASE64URL'
| 'hex' | 'HEX'
| 'latin1' | 'LATIN1'
| 'ucs-2' | 'UCS-2'
| 'ucs2' | 'UCS2'
| 'utf-8' | 'UTF-8'
| 'utf8' | 'UTF8'
| 'utf16le' | 'UTF16LE';
export interface TransitionalOptions {
silentJSONParsing?: boolean;
@ -124,13 +185,28 @@ export interface ParamsSerializerOptions extends SerializerOptions {
encode?: ParamEncoder;
}
type MaxUploadRate = number;
type MaxDownloadRate = number;
export interface AxiosProgressEvent {
loaded: number;
total?: number;
progress?: number;
bytes: number;
rate?: number;
estimated?: number;
upload?: boolean;
download?: boolean;
}
export interface AxiosRequestConfig<D = any> {
url?: string;
method?: Method | string;
baseURL?: string;
transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[];
transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[];
headers?: AxiosRequestHeaders;
headers?: RawAxiosRequestHeaders;
params?: any;
paramsSerializer?: ParamsSerializerOptions;
data?: D;
@ -143,12 +219,13 @@ export interface AxiosRequestConfig<D = any> {
responseEncoding?: responseEncoding | string;
xsrfCookieName?: string;
xsrfHeaderName?: string;
onUploadProgress?: (progressEvent: ProgressEvent) => void;
onDownloadProgress?: (progressEvent: ProgressEvent) => void;
onUploadProgress?: (progressEvent: AxiosProgressEvent) => void;
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
maxContentLength?: number;
validateStatus?: ((status: number) => boolean) | null;
maxBodyLength?: number;
maxRedirects?: number;
maxRate?: number | [MaxUploadRate, MaxDownloadRate];
beforeRedirect?: (options: Record<string, any>, responseDetails: {headers: Record<string, string>}) => void;
socketPath?: string | null;
httpAgent?: any;
@ -166,17 +243,17 @@ export interface AxiosRequestConfig<D = any> {
}
export interface HeadersDefaults {
common: AxiosRequestHeaders;
delete: AxiosRequestHeaders;
get: AxiosRequestHeaders;
head: AxiosRequestHeaders;
post: AxiosRequestHeaders;
put: AxiosRequestHeaders;
patch: AxiosRequestHeaders;
options?: AxiosRequestHeaders;
purge?: AxiosRequestHeaders;
link?: AxiosRequestHeaders;
unlink?: AxiosRequestHeaders;
common: RawAxiosRequestHeaders;
delete: RawAxiosRequestHeaders;
get: RawAxiosRequestHeaders;
head: RawAxiosRequestHeaders;
post: RawAxiosRequestHeaders;
put: RawAxiosRequestHeaders;
patch: RawAxiosRequestHeaders;
options?: RawAxiosRequestHeaders;
purge?: RawAxiosRequestHeaders;
link?: RawAxiosRequestHeaders;
unlink?: RawAxiosRequestHeaders;
}
export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
@ -184,25 +261,25 @@ export interface AxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'hea
}
export interface CreateAxiosDefaults<D = any> extends Omit<AxiosRequestConfig<D>, 'headers'> {
headers?: AxiosRequestHeaders | Partial<HeadersDefaults>;
headers?: RawAxiosRequestHeaders | Partial<HeadersDefaults>;
}
export interface AxiosResponse<T = any, D = any> {
data: T;
status: number;
statusText: string;
headers: AxiosResponseHeaders;
headers: RawAxiosResponseHeaders | AxiosResponseHeaders;
config: AxiosRequestConfig<D>;
request?: any;
}
export class AxiosError<T = unknown, D = any> extends Error {
constructor(
message?: string,
code?: string,
config?: AxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
message?: string,
code?: string,
config?: AxiosRequestConfig<D>,
request?: any,
response?: AxiosResponse<T, D>
);
config?: AxiosRequestConfig<D>;
@ -297,7 +374,7 @@ export interface AxiosInstance extends Axios {
defaults: Omit<AxiosDefaults, 'headers'> & {
headers: HeadersDefaults & {
[key: string]: string | number | boolean | undefined
[key: string]: AxiosHeaderValue
}
};
}

View File

@ -1 +1,2 @@
module.exports = require('./lib/axios');
import axios from './lib/axios.js';
export default axios;

View File

@ -6,7 +6,8 @@
'use strict';
var webpack = require('webpack');
var resolve = require('@rollup/plugin-node-resolve').default;
var commonjs = require('@rollup/plugin-commonjs');
function createCustomLauncher(browser, version, platform) {
return {
@ -19,7 +20,7 @@ function createCustomLauncher(browser, version, platform) {
module.exports = function(config) {
var customLaunchers = {};
var browsers = [];
var browsers = process.env.Browsers && process.env.Browsers.split(',');
var sauceLabs;
if (process.env.SAUCE_USERNAME || process.env.SAUCE_ACCESS_KEY) {
@ -52,7 +53,7 @@ module.exports = function(config) {
// Firefox
if (runAll || process.env.SAUCE_FIREFOX) {
customLaunchers.SL_Firefox = createCustomLauncher('firefox');
//customLaunchers.SL_Firefox = createCustomLauncher('firefox');
// customLaunchers.SL_FirefoxDev = createCustomLauncher('firefox', 'dev');
// customLaunchers.SL_FirefoxBeta = createCustomLauncher('firefox', 'beta');
}
@ -127,12 +128,12 @@ module.exports = function(config) {
'Running on Travis.'
);
browsers = ['Firefox'];
} else if (process.env.GITHUB_ACTIONS !== 'false') {
} else if (process.env.GITHUB_ACTIONS === 'true') {
console.log('Running ci on Github Actions.');
browsers = ['FirefoxHeadless', 'ChromeHeadless'];
} else {
console.log('Running locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.');
browsers = ['Firefox', 'Chrome'];
browsers = browsers || ['Chrome'];
console.log(`Running ${browsers} locally since SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are not set.`);
}
config.set({
@ -147,8 +148,8 @@ module.exports = function(config) {
// list of files / patterns to load in the browser
files: [
'test/specs/__helpers.js',
'test/specs/**/*.spec.js'
{pattern: 'test/specs/__helpers.js', watched: false},
{pattern: 'test/specs/**/*.spec.js', watched: false}
],
@ -159,8 +160,20 @@ module.exports = function(config) {
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/specs/__helpers.js': ['webpack', 'sourcemap'],
'test/specs/**/*.spec.js': ['webpack', 'sourcemap']
'test/specs/__helpers.js': ['rollup'],
'test/specs/**/*.spec.js': ['rollup']
},
rollupPreprocessor: {
plugins: [
resolve({browser: true}),
commonjs()
],
output: {
format: 'iife',
name: '_axios',
sourcemap: 'inline'
}
},

View File

@ -1,27 +1,33 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var buildFullPath = require('../core/buildFullPath');
var buildURL = require('./../helpers/buildURL');
var getProxyForUrl = require('proxy-from-env').getProxyForUrl;
var http = require('http');
var https = require('https');
var httpFollow = require('follow-redirects/http');
var httpsFollow = require('follow-redirects/https');
var url = require('url');
var zlib = require('zlib');
var VERSION = require('./../env/data').version;
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var platform = require('../platform');
var fromDataURI = require('../helpers/fromDataURI');
var stream = require('stream');
import utils from './../utils.js';
import settle from './../core/settle.js';
import buildFullPath from '../core/buildFullPath.js';
import buildURL from './../helpers/buildURL.js';
import {getProxyForUrl} from 'proxy-from-env';
import http from 'http';
import https from 'https';
import followRedirects from 'follow-redirects';
import url from 'url';
import zlib from 'zlib';
import {VERSION} from '../env/data.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import platform from '../platform/index.js';
import fromDataURI from '../helpers/fromDataURI.js';
import stream from 'stream';
import AxiosHeaders from '../core/AxiosHeaders.js';
import AxiosTransformStream from '../helpers/AxiosTransformStream.js';
import EventEmitter from 'events';
var isHttps = /https:?/;
const isBrotliSupported = utils.isFunction(zlib.createBrotliDecompress);
var supportedProtocols = platform.protocols.map(function(protocol) {
const {http: httpFollow, https: httpsFollow} = followRedirects;
const isHttps = /https:?/;
const supportedProtocols = platform.protocols.map(protocol => {
return protocol + ':';
});
@ -52,9 +58,9 @@ function dispatchBeforeRedirect(options) {
* @returns {http.ClientRequestArgs}
*/
function setProxy(options, configProxy, location) {
var proxy = configProxy;
let proxy = configProxy;
if (!proxy && proxy !== false) {
var proxyUrl = getProxyForUrl(location);
const proxyUrl = getProxyForUrl(location);
if (proxyUrl) {
proxy = url.parse(proxyUrl);
// replace 'host' since the proxy object is not a URL object
@ -68,7 +74,7 @@ function setProxy(options, configProxy, location) {
if (proxy.auth.username || proxy.auth.password) {
proxy.auth = (proxy.auth.username || '') + ':' + (proxy.auth.password || '');
}
var base64 = Buffer
const base64 = Buffer
.from(proxy.auth, 'utf8')
.toString('base64');
options.headers['Proxy-Authorization'] = 'Basic ' + base64;
@ -92,10 +98,25 @@ function setProxy(options, configProxy, location) {
}
/*eslint consistent-return:0*/
module.exports = function httpAdapter(config) {
export default function httpAdapter(config) {
return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {
var onCanceled;
function done() {
let onCanceled;
let data = config.data;
const responseType = config.responseType;
const responseEncoding = config.responseEncoding;
const method = config.method.toUpperCase();
let isFinished;
let isDone;
let rejected = false;
let req;
// temporary internal emitter until the AxiosRequest class will be implemented
const emitter = new EventEmitter();
function onFinished() {
if (isFinished) return;
isFinished = true;
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
}
@ -103,36 +124,58 @@ module.exports = function httpAdapter(config) {
if (config.signal) {
config.signal.removeEventListener('abort', onCanceled);
}
emitter.removeAllListeners();
}
var resolve = function resolve(value) {
done();
resolvePromise(value);
function done(value, isRejected) {
if (isDone) return;
isDone = true;
if (isRejected) {
rejected = true;
onFinished();
}
isRejected ? rejectPromise(value) : resolvePromise(value);
}
const resolve = function resolve(value) {
done(value);
};
var rejected = false;
var reject = function reject(value) {
done();
rejected = true;
rejectPromise(value);
const reject = function reject(value) {
done(value, true);
};
var data = config.data;
var responseType = config.responseType;
var responseEncoding = config.responseEncoding;
var method = config.method.toUpperCase();
function abort(reason) {
emitter.emit('abort', !reason || reason.type ? new CanceledError(null, config, req) : reason);
}
emitter.once('abort', reject);
if (config.cancelToken || config.signal) {
config.cancelToken && config.cancelToken.subscribe(abort);
if (config.signal) {
config.signal.aborted ? abort() : config.signal.addEventListener('abort', abort);
}
}
// Parse url
var fullPath = buildFullPath(config.baseURL, config.url);
var parsed = url.parse(fullPath);
var protocol = parsed.protocol || supportedProtocols[0];
const fullPath = buildFullPath(config.baseURL, config.url);
const parsed = url.parse(fullPath);
const protocol = parsed.protocol || supportedProtocols[0];
if (protocol === 'data:') {
var convertedData;
let convertedData;
if (method !== 'GET') {
return settle(resolve, reject, {
status: 405,
statusText: 'method not allowed',
headers: {},
config: config
config
});
}
@ -159,7 +202,7 @@ module.exports = function httpAdapter(config) {
status: 200,
statusText: 'OK',
headers: {},
config: config
config
});
}
@ -171,29 +214,23 @@ module.exports = function httpAdapter(config) {
));
}
var headers = config.headers;
var headerNames = {};
Object.keys(headers).forEach(function storeLowerName(name) {
headerNames[name.toLowerCase()] = name;
});
const headers = AxiosHeaders.from(config.headers).normalize();
// Set User-Agent (required by some servers)
// See https://github.com/axios/axios/issues/69
if ('user-agent' in headerNames) {
// User-Agent is specified; handle case where no UA header is desired
if (!headers[headerNames['user-agent']]) {
delete headers[headerNames['user-agent']];
}
// Otherwise, use specified value
} else {
// Only set header if it hasn't been set in config
headers['User-Agent'] = 'axios/' + VERSION;
}
// User-Agent is specified; handle case where no UA header is desired
// Only set header if it hasn't been set in config
headers.set('User-Agent', 'axios/' + VERSION, false);
const onDownloadProgress = config.onDownloadProgress;
const onUploadProgress = config.onUploadProgress;
const maxRate = config.maxRate;
let maxUploadRate = undefined;
let maxDownloadRate = undefined;
// support for https://www.npmjs.com/package/form-data api
if (utils.isFormData(data) && utils.isFunction(data.getHeaders)) {
Object.assign(headers, data.getHeaders());
headers.set(data.getHeaders());
} else if (data && !utils.isStream(data)) {
if (Buffer.isBuffer(data)) {
// Nothing to do...
@ -209,6 +246,9 @@ module.exports = function httpAdapter(config) {
));
}
// Add Content-Length header if data exists
headers.set('Content-Length', data.length, false);
if (config.maxBodyLength > -1 && data.length > config.maxBodyLength) {
return reject(new AxiosError(
'Request body larger than maxBodyLength limit',
@ -216,49 +256,70 @@ module.exports = function httpAdapter(config) {
config
));
}
}
// Add Content-Length header if data exists
if (!headerNames['content-length']) {
headers['Content-Length'] = data.length;
const contentLength = +headers.getContentLength();
if (utils.isArray(maxRate)) {
maxUploadRate = maxRate[0];
maxDownloadRate = maxRate[1];
} else {
maxUploadRate = maxDownloadRate = maxRate;
}
if (data && (onUploadProgress || maxUploadRate)) {
if (!utils.isStream(data)) {
data = stream.Readable.from(data, {objectMode: false});
}
data = stream.pipeline([data, new AxiosTransformStream({
length: utils.toFiniteNumber(contentLength),
maxRate: utils.toFiniteNumber(maxUploadRate)
})], utils.noop);
onUploadProgress && data.on('progress', progress => {
onUploadProgress(Object.assign(progress, {
upload: true
}));
});
}
// HTTP basic authentication
var auth = undefined;
let auth = undefined;
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
const username = config.auth.username || '';
const password = config.auth.password || '';
auth = username + ':' + password;
}
if (!auth && parsed.auth) {
var urlAuth = parsed.auth.split(':');
var urlUsername = urlAuth[0] || '';
var urlPassword = urlAuth[1] || '';
const urlAuth = parsed.auth.split(':');
const urlUsername = urlAuth[0] || '';
const urlPassword = urlAuth[1] || '';
auth = urlUsername + ':' + urlPassword;
}
if (auth && headerNames.authorization) {
delete headers[headerNames.authorization];
}
auth && headers.delete('authorization');
try {
buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, '');
} catch (err) {
var customErr = new Error(err.message);
const customErr = new Error(err.message);
customErr.config = config;
customErr.url = config.url;
customErr.exists = true;
reject(customErr);
return reject(customErr);
}
var options = {
headers.set('Accept-Encoding', 'gzip, deflate, gzip, br', false);
const options = {
path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\?/, ''),
method: method,
headers: headers,
method,
headers: headers.toJSON(),
agents: { http: config.httpAgent, https: config.httpsAgent },
auth: auth,
protocol: protocol,
auth,
protocol,
beforeRedirect: dispatchBeforeRedirect,
beforeRedirects: {}
};
@ -271,8 +332,8 @@ module.exports = function httpAdapter(config) {
setProxy(options, config.proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);
}
var transport;
var isHttpsRequest = isHttps.test(options.protocol);
let transport;
const isHttpsRequest = isHttps.test(options.protocol);
options.agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;
if (config.transport) {
transport = config.transport;
@ -300,14 +361,16 @@ module.exports = function httpAdapter(config) {
}
// Create the request
var req = transport.request(options, function handleResponse(res) {
if (req.aborted) return;
req = transport.request(options, function handleResponse(res) {
if (req.destroyed) return;
const streams = [res];
// uncompress the response body transparently if required
var responseStream = res;
let responseStream = res;
// return the last request in case of redirects
var lastRequest = res.req || req;
const lastRequest = res.req || req;
// if decompress disabled we should not decompress
if (config.decompress !== false) {
@ -323,19 +386,48 @@ module.exports = function httpAdapter(config) {
case 'compress':
case 'deflate':
// add the unzipper to the body stream processing pipeline
responseStream = responseStream.pipe(zlib.createUnzip());
streams.push(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
break;
case 'br':
if (isBrotliSupported) {
streams.push(zlib.createBrotliDecompress());
delete res.headers['content-encoding'];
}
}
}
var response = {
if (onDownloadProgress) {
const responseLength = +res.headers['content-length'];
const transformStream = new AxiosTransformStream({
length: utils.toFiniteNumber(responseLength),
maxRate: utils.toFiniteNumber(maxDownloadRate)
});
onDownloadProgress && transformStream.on('progress', progress => {
onDownloadProgress(Object.assign(progress, {
download: true
}));
});
streams.push(transformStream);
}
responseStream = streams.length > 1 ? stream.pipeline(streams, utils.noop) : streams[0];
const offListeners = stream.finished(responseStream, () => {
offListeners();
onFinished();
});
const response = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config: config,
headers: new AxiosHeaders(res.headers),
config,
request: lastRequest
};
@ -343,8 +435,9 @@ module.exports = function httpAdapter(config) {
response.data = responseStream;
settle(resolve, reject, response);
} else {
var responseBuffer = [];
var totalResponseBytes = 0;
const responseBuffer = [];
let totalResponseBytes = 0;
responseStream.on('data', function handleStreamData(chunk) {
responseBuffer.push(chunk);
totalResponseBytes += chunk.length;
@ -363,23 +456,25 @@ module.exports = function httpAdapter(config) {
if (rejected) {
return;
}
responseStream.destroy();
reject(new AxiosError(
const err = new AxiosError(
'maxContentLength size of ' + config.maxContentLength + ' exceeded',
AxiosError.ERR_BAD_RESPONSE,
config,
lastRequest
));
);
responseStream.destroy(err);
reject(err);
});
responseStream.on('error', function handleStreamError(err) {
if (req.aborted) return;
if (req.destroyed) return;
reject(AxiosError.from(err, null, config, lastRequest));
});
responseStream.on('end', function handleStreamEnd() {
try {
var responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
let responseData = responseBuffer.length === 1 ? responseBuffer[0] : Buffer.concat(responseBuffer);
if (responseType !== 'arraybuffer') {
responseData = responseData.toString(responseEncoding);
if (!responseEncoding || responseEncoding === 'utf8') {
@ -393,6 +488,18 @@ module.exports = function httpAdapter(config) {
settle(resolve, reject, response);
});
}
emitter.once('abort', err => {
if (!responseStream.destroyed) {
responseStream.emit('error', err);
responseStream.destroy();
}
});
});
emitter.once('abort', err => {
reject(err);
req.destroy(err);
});
// Handle errors
@ -411,7 +518,7 @@ module.exports = function httpAdapter(config) {
// Handle request timeout
if (config.timeout) {
// This is forcing a int timeout to avoid problems if the `req` interface doesn't handle other types.
var timeout = parseInt(config.timeout, 10);
const timeout = parseInt(config.timeout, 10);
if (isNaN(timeout)) {
reject(new AxiosError(
@ -430,9 +537,9 @@ module.exports = function httpAdapter(config) {
// And then these socket which be hang up will devouring CPU little by little.
// ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.
req.setTimeout(timeout, function handleRequestTimeout() {
req.abort();
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
if (isDone) return;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
@ -442,33 +549,34 @@ module.exports = function httpAdapter(config) {
config,
req
));
abort();
});
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
if (req.aborted) return;
req.abort();
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
};
config.cancelToken && config.cancelToken.subscribe(onCanceled);
if (config.signal) {
config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);
}
}
// Send the request
if (utils.isStream(data)) {
data.on('error', function handleStreamError(err) {
reject(AxiosError.from(err, config, null, req));
}).pipe(req);
let ended = false;
let errored = false;
data.on('end', () => {
ended = true;
});
data.once('error', err => {
errored = true;
req.destroy(err);
});
data.on('close', () => {
if (!ended && !errored) {
abort(new CanceledError('Request stream has been aborted', config, req));
}
});
data.pipe(req);
} else {
req.end(data);
}
});
};
}

33
lib/adapters/index.js Normal file
View File

@ -0,0 +1,33 @@
import utils from '../utils.js';
import httpAdapter from './http.js';
import xhrAdapter from './xhr.js';
const adapters = {
http: httpAdapter,
xhr: xhrAdapter
}
export default {
getAdapter: (nameOrAdapter) => {
if(utils.isString(nameOrAdapter)){
const adapter = adapters[nameOrAdapter];
if (!nameOrAdapter) {
throw Error(
utils.hasOwnProp(nameOrAdapter) ?
`Adapter '${nameOrAdapter}' is not available in the build` :
`Can not resolve adapter '${nameOrAdapter}'`
);
}
return adapter
}
if (!utils.isFunction(nameOrAdapter)) {
throw new TypeError('adapter is not a function');
}
return nameOrAdapter;
},
adapters
}

View File

@ -1,24 +1,53 @@
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var cookies = require('./../helpers/cookies');
var buildURL = require('./../helpers/buildURL');
var buildFullPath = require('../core/buildFullPath');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var transitionalDefaults = require('../defaults/transitional');
var AxiosError = require('../core/AxiosError');
var CanceledError = require('../cancel/CanceledError');
var parseProtocol = require('../helpers/parseProtocol');
var platform = require('../platform');
import utils from './../utils.js';
import settle from './../core/settle.js';
import cookies from './../helpers/cookies.js';
import buildURL from './../helpers/buildURL.js';
import buildFullPath from '../core/buildFullPath.js';
import isURLSameOrigin from './../helpers/isURLSameOrigin.js';
import transitionalDefaults from '../defaults/transitional.js';
import AxiosError from '../core/AxiosError.js';
import CanceledError from '../cancel/CanceledError.js';
import parseProtocol from '../helpers/parseProtocol.js';
import platform from '../platform/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
import speedometer from '../helpers/speedometer.js';
module.exports = function xhrAdapter(config) {
function progressEventReducer(listener, isDownloadStream) {
let bytesNotified = 0;
const _speedometer = speedometer(50, 250);
return e => {
const loaded = e.loaded;
const total = e.lengthComputable ? e.total : undefined;
const progressBytes = loaded - bytesNotified;
const rate = _speedometer(progressBytes);
const inRange = loaded <= total;
bytesNotified = loaded;
const data = {
loaded,
total,
progress: total ? (loaded / total) : undefined,
bytes: progressBytes,
rate: rate ? rate : undefined,
estimated: rate && total && inRange ? (total - loaded) / rate : undefined
};
data[isDownloadStream ? 'download' : 'upload'] = true;
listener(data);
};
}
export default function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.responseType;
var onCanceled;
let requestData = config.data;
const requestHeaders = AxiosHeaders.from(config.headers).normalize();
const responseType = config.responseType;
let onCanceled;
function done() {
if (config.cancelToken) {
config.cancelToken.unsubscribe(onCanceled);
@ -30,19 +59,19 @@ module.exports = function xhrAdapter(config) {
}
if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {
delete requestHeaders['Content-Type']; // Let the browser set it
requestHeaders.setContentType(false); // Let the browser set it
}
var request = new XMLHttpRequest();
let request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
const username = config.auth.username || '';
const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';
requestHeaders.set('Authorization', 'Basic ' + btoa(username + ':' + password));
}
var fullPath = buildFullPath(config.baseURL, config.url);
const fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
@ -54,16 +83,18 @@ module.exports = function xhrAdapter(config) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !responseType || responseType === 'text' || responseType === 'json' ?
const responseHeaders = AxiosHeaders.from(
'getAllResponseHeaders' in request && request.getAllResponseHeaders()
);
const responseData = !responseType || responseType === 'text' || responseType === 'json' ?
request.responseText : request.response;
var response = {
const response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
config,
request
};
settle(function _resolve(value) {
@ -125,8 +156,8 @@ module.exports = function xhrAdapter(config) {
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
var transitional = config.transitional || transitionalDefaults;
let timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';
const transitional = config.transitional || transitionalDefaults;
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
@ -145,25 +176,21 @@ module.exports = function xhrAdapter(config) {
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
const xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath))
&& config.xsrfCookieName && cookies.read(config.xsrfCookieName);
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
requestHeaders.set(config.xsrfHeaderName, xsrfValue);
}
}
// Remove Content-Type if data is undefined
requestData === undefined && requestHeaders.setContentType(null);
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
utils.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) {
request.setRequestHeader(key, val);
});
}
@ -179,22 +206,22 @@ module.exports = function xhrAdapter(config) {
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
request.addEventListener('progress', progressEventReducer(config.onDownloadProgress, true));
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
request.upload.addEventListener('progress', progressEventReducer(config.onUploadProgress));
}
if (config.cancelToken || config.signal) {
// Handle cancellation
// eslint-disable-next-line func-names
onCanceled = function(cancel) {
onCanceled = cancel => {
if (!request) {
return;
}
reject(!cancel || cancel.type ? new CanceledError(null, config, req) : cancel);
reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel);
request.abort();
request = null;
};
@ -210,7 +237,7 @@ module.exports = function xhrAdapter(config) {
requestData = null;
}
var protocol = parseProtocol(fullPath);
const protocol = parseProtocol(fullPath);
if (protocol && platform.protocols.indexOf(protocol) === -1) {
reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));
@ -221,4 +248,4 @@ module.exports = function xhrAdapter(config) {
// Send the request
request.send(requestData);
});
};
}

View File

@ -1,11 +1,20 @@
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var mergeConfig = require('./core/mergeConfig');
var defaults = require('./defaults');
var formDataToJSON = require('./helpers/formDataToJSON');
import utils from './utils.js';
import bind from './helpers/bind.js';
import Axios from './core/Axios.js';
import mergeConfig from './core/mergeConfig.js';
import defaults from './defaults/index.js';
import formDataToJSON from './helpers/formDataToJSON.js';
import CanceledError from './cancel/CanceledError.js';
import CancelToken from'./cancel/CancelToken.js';
import isCancel from'./cancel/isCancel.js';
import {VERSION} from './env/data.js';
import toFormData from './helpers/toFormData.js';
import AxiosError from '../lib/core/AxiosError.js';
import spread from './helpers/spread.js';
import isAxiosError from './helpers/isAxiosError.js';
/**
* Create an instance of Axios
*
@ -14,14 +23,14 @@ var formDataToJSON = require('./helpers/formDataToJSON');
* @returns {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
const context = new Axios(defaultConfig);
const instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
utils.extend(instance, Axios.prototype, context, {allOwnKeys: true});
// Copy context to instance
utils.extend(instance, context);
utils.extend(instance, context, {allOwnKeys: true});
// Factory for creating new instances
instance.create = function create(instanceConfig) {
@ -32,20 +41,20 @@ function createInstance(defaultConfig) {
}
// Create the default instance to be exported
var axios = createInstance(defaults);
const axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Expose Cancel & CancelToken
axios.CanceledError = require('./cancel/CanceledError');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
axios.VERSION = require('./env/data').version;
axios.toFormData = require('./helpers/toFormData');
axios.CanceledError = CanceledError;
axios.CancelToken = CancelToken;
axios.isCancel = isCancel;
axios.VERSION = VERSION;
axios.toFormData = toFormData;
// Expose AxiosError class
axios.AxiosError = require('../lib/core/AxiosError');
axios.AxiosError = AxiosError;
// alias for CanceledError for backward compatibility
axios.Cancel = axios.CanceledError;
@ -54,16 +63,14 @@ axios.Cancel = axios.CanceledError;
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
axios.spread = spread;
// Expose isAxiosError
axios.isAxiosError = require('./helpers/isAxiosError');
axios.isAxiosError = isAxiosError;
axios.formToJSON = function(thing) {
axios.formToJSON = thing => {
return formDataToJSON(utils.isHTMLForm(thing) ? new FormData(thing) : thing);
};
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
export default axios;

View File

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

View File

@ -1,7 +1,7 @@
'use strict';
var AxiosError = require('../core/AxiosError');
var utils = require('../utils');
import AxiosError from '../core/AxiosError.js';
import utils from '../utils.js';
/**
* A `CanceledError` is an object that is thrown when an operation is canceled.
@ -22,4 +22,4 @@ utils.inherits(CanceledError, AxiosError, {
__CANCEL__: true
});
module.exports = CanceledError;
export default CanceledError;

View File

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

View File

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

View File

@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* Create an Error with the specified message, config, error code, request and response.
@ -52,8 +52,8 @@ utils.inherits(AxiosError, Error, {
}
});
var prototype = AxiosError.prototype;
var descriptors = {};
const prototype = AxiosError.prototype;
const descriptors = {};
[
'ERR_BAD_OPTION_VALUE',
@ -69,7 +69,7 @@ var descriptors = {};
'ERR_NOT_SUPPORT',
'ERR_INVALID_URL'
// eslint-disable-next-line func-names
].forEach(function(code) {
].forEach(code => {
descriptors[code] = {value: code};
});
@ -77,11 +77,13 @@ Object.defineProperties(AxiosError, descriptors);
Object.defineProperty(prototype, 'isAxiosError', {value: true});
// eslint-disable-next-line func-names
AxiosError.from = function(error, code, config, request, response, customProps) {
var axiosError = Object.create(prototype);
AxiosError.from = (error, code, config, request, response, customProps) => {
const axiosError = Object.create(prototype);
utils.toFlatObject(error, axiosError, function filter(obj) {
return obj !== Error.prototype;
}, prop => {
return prop !== 'isAxiosError';
});
AxiosError.call(axiosError, error.message, code, config, request, response);
@ -95,4 +97,4 @@ AxiosError.from = function(error, code, config, request, response, customProps)
return axiosError;
};
module.exports = AxiosError;
export default AxiosError;

274
lib/core/AxiosHeaders.js Normal file
View File

@ -0,0 +1,274 @@
'use strict';
import utils from '../utils.js';
import parseHeaders from '../helpers/parseHeaders.js';
const $internals = Symbol('internals');
const $defaults = Symbol('defaults');
function normalizeHeader(header) {
return header && String(header).trim().toLowerCase();
}
function normalizeValue(value) {
if (value === false || value == null) {
return value;
}
return String(value);
}
function parseTokens(str) {
const tokens = Object.create(null);
const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let match;
while ((match = tokensRE.exec(str))) {
tokens[match[1]] = match[2];
}
return tokens;
}
function matchHeaderValue(context, value, header, filter) {
if (utils.isFunction(filter)) {
return filter.call(this, value, header);
}
if (!utils.isString(value)) return;
if (utils.isString(filter)) {
return value.indexOf(filter) !== -1;
}
if (utils.isRegExp(filter)) {
return filter.test(value);
}
}
function formatHeader(header) {
return header.trim()
.toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str) => {
return char.toUpperCase() + str;
});
}
function buildAccessors(obj, header) {
const accessorName = utils.toCamelCase(' ' + header);
['get', 'set', 'has'].forEach(methodName => {
Object.defineProperty(obj, methodName + accessorName, {
value: function(arg1, arg2, arg3) {
return this[methodName].call(this, header, arg1, arg2, arg3);
},
configurable: true
});
});
}
function findKey(obj, key) {
key = key.toLowerCase();
const keys = Object.keys(obj);
let i = keys.length;
let _key;
while (i-- > 0) {
_key = keys[i];
if (key === _key.toLowerCase()) {
return _key;
}
}
return null;
}
function AxiosHeaders(headers, defaults) {
headers && this.set(headers);
this[$defaults] = defaults || null;
}
Object.assign(AxiosHeaders.prototype, {
set: function(header, valueOrRewrite, rewrite) {
const self = this;
function setHeader(_value, _header, _rewrite) {
const lHeader = normalizeHeader(_header);
if (!lHeader) {
throw new Error('header name must be a non-empty string');
}
const key = findKey(self, lHeader);
if (key && _rewrite !== true && (self[key] === false || _rewrite === false)) {
return;
}
if (utils.isArray(_value)) {
_value = _value.map(normalizeValue);
} else {
_value = normalizeValue(_value);
}
self[key || _header] = _value;
}
if (utils.isPlainObject(header)) {
utils.forEach(header, (_value, _header) => {
setHeader(_value, _header, valueOrRewrite);
});
} else {
setHeader(valueOrRewrite, header, rewrite);
}
return this;
},
get: function(header, parser) {
header = normalizeHeader(header);
if (!header) return undefined;
const key = findKey(this, header);
if (key) {
const value = this[key];
if (!parser) {
return value;
}
if (parser === true) {
return parseTokens(value);
}
if (utils.isFunction(parser)) {
return parser.call(this, value, key);
}
if (utils.isRegExp(parser)) {
return parser.exec(value);
}
throw new TypeError('parser must be boolean|regexp|function');
}
},
has: function(header, matcher) {
header = normalizeHeader(header);
if (header) {
const key = findKey(this, header);
return !!(key && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
}
return false;
},
delete: function(header, matcher) {
const self = this;
let deleted = false;
function deleteHeader(_header) {
_header = normalizeHeader(_header);
if (_header) {
const key = findKey(self, _header);
if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
delete self[key];
deleted = true;
}
}
}
if (utils.isArray(header)) {
header.forEach(deleteHeader);
} else {
deleteHeader(header);
}
return deleted;
},
clear: function() {
return Object.keys(this).forEach(this.delete.bind(this));
},
normalize: function(format) {
const self = this;
const headers = {};
utils.forEach(this, (value, header) => {
const key = findKey(headers, header);
if (key) {
self[key] = normalizeValue(value);
delete self[header];
return;
}
const normalized = format ? formatHeader(header) : String(header).trim();
if (normalized !== header) {
delete self[header];
}
self[normalized] = normalizeValue(value);
headers[normalized] = true;
});
return this;
},
toJSON: function() {
const obj = Object.create(null);
utils.forEach(Object.assign({}, this[$defaults] || null, this),
(value, header) => {
if (value == null || value === false) return;
obj[header] = utils.isArray(value) ? value.join(', ') : value;
});
return obj;
}
});
Object.assign(AxiosHeaders, {
from: function(thing) {
if (utils.isString(thing)) {
return new this(parseHeaders(thing));
}
return thing instanceof this ? thing : new this(thing);
},
accessor: function(header) {
const internals = this[$internals] = (this[$internals] = {
accessors: {}
});
const accessors = internals.accessors;
const prototype = this.prototype;
function defineAccessor(_header) {
const lHeader = normalizeHeader(_header);
if (!accessors[lHeader]) {
buildAccessors(prototype, _header);
accessors[lHeader] = true;
}
}
utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);
return this;
}
});
AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent']);
utils.freezeMethods(AxiosHeaders.prototype);
utils.freezeMethods(AxiosHeaders);
export default AxiosHeaders;

View File

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

View File

@ -1,7 +1,7 @@
'use strict';
var isAbsoluteURL = require('../helpers/isAbsoluteURL');
var combineURLs = require('../helpers/combineURLs');
import isAbsoluteURL from '../helpers/isAbsoluteURL.js';
import combineURLs from '../helpers/combineURLs.js';
/**
* Creates a new URL by combining the baseURL with the requestedURL,
@ -13,9 +13,9 @@ var combineURLs = require('../helpers/combineURLs');
*
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
export default function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
}

View File

@ -1,11 +1,10 @@
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
var CanceledError = require('../cancel/CanceledError');
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
import transformData from './transformData.js';
import isCancel from '../cancel/isCancel.js';
import defaults from '../defaults/index.js';
import CanceledError from '../cancel/CanceledError.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
/**
* Throws a `CanceledError` if cancellation has been requested.
@ -31,39 +30,18 @@ function throwIfCancellationRequested(config) {
*
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
export default function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
config.headers = AxiosHeaders.from(config.headers);
// Transform request data
config.data = transformData.call(
config,
config.data,
config.headers,
null,
config.transformRequest
);
normalizeHeaderName(config.headers, 'Accept');
normalizeHeaderName(config.headers, 'Content-Type');
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
const adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
@ -71,12 +49,12 @@ module.exports = function dispatchRequest(config) {
// Transform response data
response.data = transformData.call(
config,
response.data,
response.headers,
response.status,
config.transformResponse
config.transformResponse,
response
);
response.headers = AxiosHeaders.from(response.headers);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
@ -86,14 +64,13 @@ module.exports = function dispatchRequest(config) {
if (reason && reason.response) {
reason.response.data = transformData.call(
config,
reason.response.data,
reason.response.headers,
reason.response.status,
config.transformResponse
config.transformResponse,
reason.response
);
reason.response.headers = AxiosHeaders.from(reason.response.headers);
}
}
return Promise.reject(reason);
});
};
}

View File

@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* Config-specific merge-function which creates a new config-object
@ -11,10 +11,10 @@ var utils = require('../utils');
*
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
export default function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
const config = {};
function getMergedValue(target, source) {
if (utils.isPlainObject(target) && utils.isPlainObject(source)) {
@ -61,7 +61,7 @@ module.exports = function mergeConfig(config1, config2) {
}
}
var mergeMap = {
const mergeMap = {
'url': valueFromConfig2,
'method': valueFromConfig2,
'data': valueFromConfig2,
@ -92,10 +92,10 @@ module.exports = function mergeConfig(config1, config2) {
};
utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {
var merge = mergeMap[prop] || mergeDeepProperties;
var configValue = merge(prop);
const merge = mergeMap[prop] || mergeDeepProperties;
const configValue = merge(prop);
(utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);
});
return config;
};
}

View File

@ -1,6 +1,6 @@
'use strict';
var AxiosError = require('./AxiosError');
import AxiosError from './AxiosError.js';
/**
* Resolve or reject a Promise based on response status.
@ -11,8 +11,8 @@ var AxiosError = require('./AxiosError');
*
* @returns {object} The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
export default function settle(resolve, reject, response) {
const validateStatus = response.config.validateStatus;
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
@ -24,4 +24,4 @@ module.exports = function settle(resolve, reject, response) {
response
));
}
};
}

View File

@ -1,24 +1,28 @@
'use strict';
var utils = require('./../utils');
var defaults = require('../defaults');
import utils from './../utils.js';
import defaults from '../defaults/index.js';
import AxiosHeaders from '../core/AxiosHeaders.js';
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Number} status HTTP status code
* @param {Array|Function} fns A single function or Array of functions
* @param {?Object} response The response object
*
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, status, fns) {
var context = this || defaults;
/*eslint no-param-reassign:0*/
export default function transformData(fns, response) {
const config = this || defaults;
const context = response || config;
const headers = AxiosHeaders.from(context.headers);
let data = context.data;
utils.forEach(fns, function transform(fn) {
data = fn.call(context, data, headers, status);
data = fn.call(config, data, headers.normalize(), response ? response.status : undefined);
});
headers.normalize();
return data;
};
}

View File

@ -1,34 +1,18 @@
'use strict';
var utils = require('../utils');
var normalizeHeaderName = require('../helpers/normalizeHeaderName');
var AxiosError = require('../core/AxiosError');
var transitionalDefaults = require('./transitional');
var toFormData = require('../helpers/toFormData');
var toURLEncodedForm = require('../helpers/toURLEncodedForm');
var platform = require('../platform');
var formDataToJSON = require('../helpers/formDataToJSON');
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import transitionalDefaults from './transitional.js';
import toFormData from '../helpers/toFormData.js';
import toURLEncodedForm from '../helpers/toURLEncodedForm.js';
import platform from '../platform/index.js';
import formDataToJSON from '../helpers/formDataToJSON.js';
import adapters from '../adapters/index.js';
var DEFAULT_CONTENT_TYPE = {
const DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
/**
* If the headers object is not undefined and the Content-Type property of the headers object
* is undefined, then set the Content-Type property of the headers object to the value passed
* in
*
* @param {Object<string, string>} headers - The headers object that will be sent to the server.
* @param {any} value - The value of the Content-Type header.
*
* @returns {void}
*/
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
/**
* If the browser has an XMLHttpRequest object, use the XHR adapter, otherwise use the HTTP
* adapter
@ -36,13 +20,13 @@ function setContentTypeIfUnset(headers, value) {
* @returns {Function}
*/
function getDefaultAdapter() {
var adapter;
let adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = require('../adapters/xhr');
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
adapter = adapters.getAdapter('xhr');
} else if (typeof process !== 'undefined' && utils.kindOf(process) === 'process') {
// For node use HTTP adapter
adapter = require('../adapters/http');
adapter = adapters.getAdapter('http');
}
return adapter;
}
@ -72,25 +56,22 @@ function stringifySafely(rawValue, parser, encoder) {
return (encoder || JSON.stringify)(rawValue);
}
var defaults = {
const defaults = {
transitional: transitionalDefaults,
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
var contentType = headers && headers['Content-Type'] || '';
var hasJSONContentType = contentType.indexOf('application/json') > -1;
var isObjectPayload = utils.isObject(data);
const contentType = headers.getContentType() || '';
const hasJSONContentType = contentType.indexOf('application/json') > -1;
const isObjectPayload = utils.isObject(data);
if (isObjectPayload && utils.isHTMLForm(data)) {
data = new FormData(data);
}
var isFormData = utils.isFormData(data);
const isFormData = utils.isFormData(data);
if (isFormData) {
if (!hasJSONContentType) {
@ -111,19 +92,19 @@ var defaults = {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
headers.setContentType('application/x-www-form-urlencoded;charset=utf-8', false);
return data.toString();
}
var isFileList;
let isFileList;
if (isObjectPayload) {
if (contentType.indexOf('application/x-www-form-urlencoded') !== -1) {
if (contentType.indexOf('application/x-www-form-urlencoded') > -1) {
return toURLEncodedForm(data, this.formSerializer).toString();
}
if ((isFileList = utils.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) {
var _FormData = this.env && this.env.FormData;
const _FormData = this.env && this.env.FormData;
return toFormData(
isFileList ? {'files[]': data} : data,
@ -134,7 +115,7 @@ var defaults = {
}
if (isObjectPayload || hasJSONContentType ) {
setContentTypeIfUnset(headers, 'application/json');
headers.setContentType('application/json', false);
return stringifySafely(data);
}
@ -142,13 +123,13 @@ var defaults = {
}],
transformResponse: [function transformResponse(data) {
var transitional = this.transitional || defaults.transitional;
var forcedJSONParsing = transitional && transitional.forcedJSONParsing;
var JSONRequested = this.responseType === 'json';
const transitional = this.transitional || defaults.transitional;
const forcedJSONParsing = transitional && transitional.forcedJSONParsing;
const JSONRequested = this.responseType === 'json';
if (data && utils.isString(data) && ((forcedJSONParsing && !this.responseType) || JSONRequested)) {
var silentJSONParsing = transitional && transitional.silentJSONParsing;
var strictJSONParsing = !silentJSONParsing && JSONRequested;
const silentJSONParsing = transitional && transitional.silentJSONParsing;
const strictJSONParsing = !silentJSONParsing && JSONRequested;
try {
return JSON.parse(data);
@ -201,4 +182,4 @@ utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
export default defaults;

View File

@ -1,6 +1,6 @@
'use strict';
module.exports = {
export default {
silentJSONParsing: true,
forcedJSONParsing: true,
clarifyTimeoutError: false

View File

@ -1,2 +1,2 @@
// eslint-disable-next-line strict
module.exports = require('form-data');
import FormData from 'form-data';
export default FormData;

4
lib/env/data.js vendored
View File

@ -1,3 +1 @@
module.exports = {
"version": "1.0.0-alpha.1"
};
export const VERSION = "1.0.0-alpha.1";

View File

@ -0,0 +1,191 @@
'use strict';
import stream from 'stream';
import utils from '../utils.js';
import throttle from './throttle.js';
import speedometer from './speedometer.js';
const kInternals = Symbol('internals');
class AxiosTransformStream extends stream.Transform{
constructor(options) {
options = utils.toFlatObject(options, {
maxRate: 0,
chunkSize: 64 * 1024,
minChunkSize: 100,
timeWindow: 500,
ticksRate: 2,
samplesCount: 15
}, null, (prop, source) => {
return !utils.isUndefined(source[prop]);
});
super({
readableHighWaterMark: options.chunkSize
});
const self = this;
const internals = this[kInternals] = {
length: options.length,
timeWindow: options.timeWindow,
ticksRate: options.ticksRate,
chunkSize: options.chunkSize,
maxRate: options.maxRate,
minChunkSize: options.minChunkSize,
bytesSeen: 0,
isCaptured: false,
notifiedBytesLoaded: 0,
ts: Date.now(),
bytes: 0,
onReadCallback: null
};
const _speedometer = speedometer(internals.ticksRate * options.samplesCount, internals.timeWindow);
this.on('newListener', event => {
if (event === 'progress') {
if (!internals.isCaptured) {
internals.isCaptured = true;
}
}
});
let bytesNotified = 0;
internals.updateProgress = throttle(function throttledHandler() {
const totalBytes = internals.length;
const bytesTransferred = internals.bytesSeen;
const progressBytes = bytesTransferred - bytesNotified;
if (!progressBytes || self.destroyed) return;
const rate = _speedometer(progressBytes);
bytesNotified = bytesTransferred;
process.nextTick(() => {
self.emit('progress', {
'loaded': bytesTransferred,
'total': totalBytes,
'progress': totalBytes ? (bytesTransferred / totalBytes) : undefined,
'bytes': progressBytes,
'rate': rate ? rate : undefined,
'estimated': rate && totalBytes && bytesTransferred <= totalBytes ?
(totalBytes - bytesTransferred) / rate : undefined
});
});
}, internals.ticksRate);
const onFinish = () => {
internals.updateProgress(true);
};
this.once('end', onFinish);
this.once('error', onFinish);
}
_read(size) {
const internals = this[kInternals];
if (internals.onReadCallback) {
internals.onReadCallback();
}
return super._read(size);
}
_transform(chunk, encoding, callback) {
const self = this;
const internals = this[kInternals];
const maxRate = internals.maxRate;
const readableHighWaterMark = this.readableHighWaterMark;
const timeWindow = internals.timeWindow;
const divider = 1000 / timeWindow;
const bytesThreshold = (maxRate / divider);
const minChunkSize = internals.minChunkSize !== false ? Math.max(internals.minChunkSize, bytesThreshold * 0.01) : 0;
function pushChunk(_chunk, _callback) {
const bytes = Buffer.byteLength(_chunk);
internals.bytesSeen += bytes;
internals.bytes += bytes;
if (internals.isCaptured) {
internals.updateProgress();
}
if (self.push(_chunk)) {
process.nextTick(_callback);
} else {
internals.onReadCallback = () => {
internals.onReadCallback = null;
process.nextTick(_callback);
};
}
}
const transformChunk = (_chunk, _callback) => {
const chunkSize = Buffer.byteLength(_chunk);
let chunkRemainder = null;
let maxChunkSize = readableHighWaterMark;
let bytesLeft;
let passed = 0;
if (maxRate) {
const now = Date.now();
if (!internals.ts || (passed = (now - internals.ts)) >= timeWindow) {
internals.ts = now;
bytesLeft = bytesThreshold - internals.bytes;
internals.bytes = bytesLeft < 0 ? -bytesLeft : 0;
passed = 0;
}
bytesLeft = bytesThreshold - internals.bytes;
}
if (maxRate) {
if (bytesLeft <= 0) {
// next time window
return setTimeout(() => {
_callback(null, _chunk);
}, timeWindow - passed);
}
if (bytesLeft < maxChunkSize) {
maxChunkSize = bytesLeft;
}
}
if (maxChunkSize && chunkSize > maxChunkSize && (chunkSize - maxChunkSize) > minChunkSize) {
chunkRemainder = _chunk.subarray(maxChunkSize);
_chunk = _chunk.subarray(0, maxChunkSize);
}
pushChunk(_chunk, chunkRemainder ? () => {
process.nextTick(_callback, null, chunkRemainder);
} : _callback);
};
transformChunk(chunk, function transformNextChunk(err, _chunk) {
if (err) {
return callback(err);
}
if (_chunk) {
transformChunk(_chunk, transformNextChunk);
} else {
callback(null);
}
});
}
setLength(length) {
this[kInternals].length = +length;
return this;
}
}
export default AxiosTransformStream;

View File

@ -1,6 +1,6 @@
'use strict';
var toFormData = require('./toFormData');
import toFormData from './toFormData.js';
/**
* It encodes a string by replacing all characters that are not in the unreserved set with
@ -11,7 +11,7 @@ var toFormData = require('./toFormData');
* @returns {string} The encoded string.
*/
function encode(str) {
var charMap = {
const charMap = {
'!': '%21',
"'": '%27',
'(': '%28',
@ -20,7 +20,7 @@ function encode(str) {
'%20': '+',
'%00': '\x00'
};
return encodeURIComponent(str).replace(/[!'\(\)~]|%20|%00/g, function replacer(match) {
return encodeURIComponent(str).replace(/[!'()~]|%20|%00/g, function replacer(match) {
return charMap[match];
});
}
@ -39,14 +39,14 @@ function AxiosURLSearchParams(params, options) {
params && toFormData(params, this, options);
}
var prototype = AxiosURLSearchParams.prototype;
const prototype = AxiosURLSearchParams.prototype;
prototype.append = function append(name, value) {
this._pairs.push([name, value]);
};
prototype.toString = function toString(encoder) {
var _encode = encoder ? function(value) {
const _encode = encoder ? function(value) {
return encoder.call(this, value, encode);
} : encode;
@ -55,4 +55,4 @@ prototype.toString = function toString(encoder) {
}, '').join('&');
};
module.exports = AxiosURLSearchParams;
export default AxiosURLSearchParams;

View File

@ -1,7 +1,7 @@
'use strict';
module.exports = function bind(fn, thisArg) {
export default function bind(fn, thisArg) {
return function wrap() {
return fn.apply(thisArg, arguments);
};
};
}

View File

@ -1,7 +1,7 @@
'use strict';
var utils = require('../utils');
var AxiosURLSearchParams = require('../helpers/AxiosURLSearchParams');
import utils from '../utils.js';
import AxiosURLSearchParams from '../helpers/AxiosURLSearchParams.js';
/**
* It replaces all instances of the characters `:`, `$`, `,`, `+`, `[`, and `]` with their
@ -30,21 +30,21 @@ function encode(val) {
*
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, options) {
export default function buildURL(url, params, options) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var hashmarkIndex = url.indexOf('#');
const hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
var _encode = options && options.encode || encode;
const _encode = options && options.encode || encode;
var serializerParams = utils.isURLSearchParams(params) ?
const serializerParams = utils.isURLSearchParams(params) ?
params.toString() :
new AxiosURLSearchParams(params, options).toString(_encode);
@ -53,4 +53,4 @@ module.exports = function buildURL(url, params, options) {
}
return url;
};
}

View File

@ -8,8 +8,8 @@
*
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
export default function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
}

View File

@ -1,53 +1,51 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
module.exports = (
utils.isStandardBrowserEnv() ?
export default utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
const cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
const match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})();

View File

@ -12,7 +12,7 @@
*
* @returns {void}
*/
module.exports = function deprecatedMethod(method, instead, docs) {
export default function deprecatedMethod(method, instead, docs) {
try {
console.warn(
'DEPRECATED method `' + method + '`.' +
@ -23,4 +23,4 @@ module.exports = function deprecatedMethod(method, instead, docs) {
console.warn('For more information about usage see ' + docs);
}
} catch (e) { /* Ignore */ }
};
}

View File

@ -1,6 +1,6 @@
'use strict';
var utils = require('../utils');
import utils from '../utils.js';
/**
* It takes a string like `foo[x][y][z]` and returns an array like `['foo', 'x', 'y', 'z']
@ -14,7 +14,7 @@ function parsePropPath(name) {
// foo.x.y.z
// foo-x-y-z
// foo x y z
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(function(match) {
return utils.matchAll(/\w+|\[(\w*)]/g, name).map(match => {
return match[0] === '[]' ? '' : match[1] || match[0];
});
}
@ -27,11 +27,11 @@ function parsePropPath(name) {
* @returns An object with the same keys and values as the array.
*/
function arrayToObject(arr) {
var obj = {};
var keys = Object.keys(arr);
var i;
var len = keys.length;
var key;
const obj = {};
const keys = Object.keys(arr);
let i;
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
obj[key] = arr[key];
@ -48,13 +48,13 @@ function arrayToObject(arr) {
*/
function formDataToJSON(formData) {
function buildPath(path, value, target, index) {
var name = path[index++];
var isNumericKey = Number.isFinite(+name);
var isLast = index >= path.length;
let name = path[index++];
const isNumericKey = Number.isFinite(+name);
const isLast = index >= path.length;
name = !name && utils.isArray(target) ? target.length : name;
if (isLast) {
if (utils.hasOwnProperty(target, name)) {
if (utils.hasOwnProp(target, name)) {
target[name] = [target[name], value];
} else {
target[name] = value;
@ -67,7 +67,7 @@ function formDataToJSON(formData) {
target[name] = [];
}
var result = buildPath(path, value, target[name], index);
const result = buildPath(path, value, target[name], index);
if (result && utils.isArray(target[name])) {
target[name] = arrayToObject(target[name]);
@ -77,9 +77,9 @@ function formDataToJSON(formData) {
}
if (utils.isFormData(formData) && utils.isFunction(formData.entries)) {
var obj = {};
const obj = {};
utils.forEachEntry(formData, function(name, value) {
utils.forEachEntry(formData, (name, value) => {
buildPath(parsePropPath(name), value, obj, 0);
});
@ -89,4 +89,4 @@ function formDataToJSON(formData) {
return null;
}
module.exports = formDataToJSON;
export default formDataToJSON;

View File

@ -1,10 +1,10 @@
'use strict';
var AxiosError = require('../core/AxiosError');
var parseProtocol = require('./parseProtocol');
var platform = require('../platform');
import AxiosError from '../core/AxiosError.js';
import parseProtocol from './parseProtocol.js';
import platform from '../platform/index.js';
var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
const DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
/**
* Parse data uri to a Buffer or Blob
@ -16,9 +16,9 @@ var DATA_URL_PATTERN = /^(?:([^;]+);)?(?:[^;]+;)?(base64|),([\s\S]*)$/;
*
* @returns {Buffer|Blob}
*/
module.exports = function fromDataURI(uri, asBlob, options) {
var _Blob = options && options.Blob || platform.classes.Blob;
var protocol = parseProtocol(uri);
export default function fromDataURI(uri, asBlob, options) {
const _Blob = options && options.Blob || platform.classes.Blob;
const protocol = parseProtocol(uri);
if (asBlob === undefined && _Blob) {
asBlob = true;
@ -27,16 +27,16 @@ module.exports = function fromDataURI(uri, asBlob, options) {
if (protocol === 'data') {
uri = protocol.length ? uri.slice(protocol.length + 1) : uri;
var match = DATA_URL_PATTERN.exec(uri);
const match = DATA_URL_PATTERN.exec(uri);
if (!match) {
throw new AxiosError('Invalid URL', AxiosError.ERR_INVALID_URL);
}
var mime = match[1];
var isBase64 = match[2];
var body = match[3];
var buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
const mime = match[1];
const isBase64 = match[2];
const body = match[3];
const buffer = Buffer.from(decodeURIComponent(body), isBase64 ? 'base64' : 'utf8');
if (asBlob) {
if (!_Blob) {
@ -50,4 +50,4 @@ module.exports = function fromDataURI(uri, asBlob, options) {
}
throw new AxiosError('Unsupported protocol ' + protocol, AxiosError.ERR_NOT_SUPPORT);
};
}

View File

@ -7,9 +7,9 @@
*
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
export default function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
}

View File

@ -1,6 +1,6 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
/**
* Determines whether the payload is an error thrown by Axios
@ -9,6 +9,6 @@ var utils = require('./../utils');
*
* @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
*/
module.exports = function isAxiosError(payload) {
export default function isAxiosError(payload) {
return utils.isObject(payload) && (payload.isAxiosError === true);
};
}

View File

@ -1,68 +1,66 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
module.exports = (
utils.isStandardBrowserEnv() ?
export default utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
const msie = /(msie|trident)/i.test(navigator.userAgent);
const urlParsingNode = document.createElement('a');
let originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
let href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
href = urlParsingNode.href;
}
originURL = resolveURL(window.location.href);
urlParsingNode.setAttribute('href', href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
})() :
}
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
const parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})();

View File

@ -1,12 +0,0 @@
'use strict';
var utils = require('../utils');
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};

View File

@ -1,2 +1,2 @@
// eslint-disable-next-line strict
module.exports = null;
export default null;

View File

@ -1,15 +1,15 @@
'use strict';
var utils = require('./../utils');
import utils from './../utils.js';
// Headers whose duplicates are ignored by node
// RawAxiosHeaders whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
const ignoreDuplicateOf = utils.toObjectSet([
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
]);
/**
* Parse headers into an object
@ -21,32 +21,33 @@ var ignoreDuplicateOf = [
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @param {String} rawHeaders Headers needing to be parsed
*
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
export default rawHeaders => {
const parsed = {};
let key;
let val;
let i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
rawHeaders && rawHeaders.split('\n').forEach(function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.slice(0, i)).toLowerCase();
val = utils.trim(line.slice(i + 1));
key = line.substring(0, i).trim().toLowerCase();
val = line.substring(i + 1).trim();
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
if (!key || (parsed[key] && ignoreDuplicateOf[key])) {
return;
}
if (key === 'set-cookie') {
if (parsed[key]) {
parsed[key].push(val);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
parsed[key] = [val];
}
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
});

View File

@ -1,6 +1,6 @@
'use strict';
module.exports = function parseProtocol(url) {
var match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
export default function parseProtocol(url) {
const match = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url);
return match && match[1] || '';
};
}

View File

@ -0,0 +1,55 @@
'use strict';
/**
* Calculate data maxRate
* @param {Number} [samplesCount= 10]
* @param {Number} [min= 1000]
* @returns {Function}
*/
function speedometer(samplesCount, min) {
samplesCount = samplesCount || 10;
const bytes = new Array(samplesCount);
const timestamps = new Array(samplesCount);
let head = 0;
let tail = 0;
let firstSampleTS;
min = min !== undefined ? min : 1000;
return function push(chunkLength) {
const now = Date.now();
const startedAt = timestamps[tail];
if (!firstSampleTS) {
firstSampleTS = now;
}
bytes[head] = chunkLength;
timestamps[head] = now;
let i = tail;
let bytesCount = 0;
while (i !== head) {
bytesCount += bytes[i++];
i = i % samplesCount;
}
head = (head + 1) % samplesCount;
if (head === tail) {
tail = (tail + 1) % samplesCount;
}
if (now - firstSampleTS < min) {
return;
}
const passed = startedAt && now - startedAt;
return passed ? Math.round(bytesCount * 1000 / passed) : undefined;
};
}
export default speedometer;

View File

@ -21,8 +21,8 @@
*
* @returns {Function}
*/
module.exports = function spread(callback) {
export default function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
}

33
lib/helpers/throttle.js Normal file
View File

@ -0,0 +1,33 @@
'use strict';
/**
* Throttle decorator
* @param {Function} fn
* @param {Number} freq
* @return {Function}
*/
function throttle(fn, freq) {
let timestamp = 0;
const threshold = 1000 / freq;
let timer = null;
return function throttled(force, args) {
const now = Date.now();
if (force || now - timestamp > threshold) {
if (timer) {
clearTimeout(timer);
timer = null;
}
timestamp = now;
return fn.apply(null, args);
}
if (!timer) {
timer = setTimeout(() => {
timer = null;
timestamp = Date.now();
return fn.apply(null, args);
}, threshold - (now - timestamp));
}
};
}
export default throttle;

View File

@ -1,8 +1,8 @@
'use strict';
var utils = require('../utils');
var AxiosError = require('../core/AxiosError');
var envFormData = require('../env/classes/FormData');
import utils from '../utils.js';
import AxiosError from '../core/AxiosError.js';
import envFormData from '../env/classes/FormData.js';
/**
* Determines if the given thing is a array or js object.
@ -55,7 +55,7 @@ function isFlatArray(arr) {
return utils.isArray(arr) && !arr.some(isVisitable);
}
var predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
const predicates = utils.toFlatObject(utils, {}, null, function filter(prop) {
return /^is[A-Z]/.test(prop);
});
@ -111,13 +111,13 @@ function toFormData(obj, formData, options) {
return !utils.isUndefined(source[option]);
});
var metaTokens = options.metaTokens;
const metaTokens = options.metaTokens;
// eslint-disable-next-line no-use-before-define
var visitor = options.visitor || defaultVisitor;
var dots = options.dots;
var indexes = options.indexes;
var _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
var useBlob = _Blob && isSpecCompliant(formData);
const visitor = options.visitor || defaultVisitor;
const dots = options.dots;
const indexes = options.indexes;
const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob;
const useBlob = _Blob && isSpecCompliant(formData);
if (!utils.isFunction(visitor)) {
throw new TypeError('visitor must be a function');
@ -152,7 +152,7 @@ function toFormData(obj, formData, options) {
* @returns {boolean} return true to visit the each prop of the value recursively
*/
function defaultVisitor(value, key, path) {
var arr = value;
let arr = value;
if (value && !path && typeof value === 'object') {
if (utils.endsWith(key, '{}')) {
@ -187,12 +187,12 @@ function toFormData(obj, formData, options) {
return false;
}
var stack = [];
const stack = [];
var exposedHelpers = Object.assign(predicates, {
defaultVisitor: defaultVisitor,
convertValue: convertValue,
isVisitable: isVisitable
const exposedHelpers = Object.assign(predicates, {
defaultVisitor,
convertValue,
isVisitable
});
function build(value, path) {
@ -205,7 +205,7 @@ function toFormData(obj, formData, options) {
stack.push(value);
utils.forEach(value, function each(el, key) {
var result = !utils.isUndefined(el) && visitor.call(
const result = !utils.isUndefined(el) && visitor.call(
formData, el, utils.isString(key) ? key.trim() : key, path, exposedHelpers
);
@ -226,4 +226,4 @@ function toFormData(obj, formData, options) {
return formData;
}
module.exports = toFormData;
export default toFormData;

View File

@ -1,10 +1,10 @@
'use strict';
var utils = require('../utils');
var toFormData = require('./toFormData');
var platform = require('../platform/');
import utils from '../utils.js';
import toFormData from './toFormData.js';
import platform from '../platform/index.js';
module.exports = function toURLEncodedForm(data, options) {
export default function toURLEncodedForm(data, options) {
return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({
visitor: function(value, key, path, helpers) {
if (platform.isNode && utils.isBuffer(value)) {
@ -15,4 +15,4 @@ module.exports = function toURLEncodedForm(data, options) {
return helpers.defaultVisitor.apply(this, arguments);
}
}, options));
};
}

View File

@ -1,18 +1,18 @@
'use strict';
var VERSION = require('../env/data').version;
var AxiosError = require('../core/AxiosError');
import {VERSION} from '../env/data.js';
import AxiosError from '../core/AxiosError.js';
var validators = {};
const validators = {};
// eslint-disable-next-line func-names
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {
['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach((type, i) => {
validators[type] = function validator(thing) {
return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;
};
});
var deprecatedWarnings = {};
const deprecatedWarnings = {};
/**
* Transitional option validator
@ -29,7 +29,7 @@ validators.transitional = function transitional(validator, version, message) {
}
// eslint-disable-next-line func-names
return function(value, opt, opts) {
return (value, opt, opts) => {
if (validator === false) {
throw new AxiosError(
formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),
@ -66,14 +66,14 @@ function assertOptions(options, schema, allowUnknown) {
if (typeof options !== 'object') {
throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);
}
var keys = Object.keys(options);
var i = keys.length;
const keys = Object.keys(options);
let i = keys.length;
while (i-- > 0) {
var opt = keys[i];
var validator = schema[opt];
const opt = keys[i];
const validator = schema[opt];
if (validator) {
var value = options[opt];
var result = value === undefined || validator(value, opt, options);
const value = options[opt];
const result = value === undefined || validator(value, opt, options);
if (result !== true) {
throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);
}
@ -85,7 +85,7 @@ function assertOptions(options, schema, allowUnknown) {
}
}
module.exports = {
assertOptions: assertOptions,
validators: validators
export default {
assertOptions,
validators
};

View File

@ -1,3 +1,3 @@
'use strict';
module.exports = FormData;
export default FormData;

View File

@ -1,5 +1,4 @@
'use strict';
var AxiosURLSearchParams = require('../../../helpers/AxiosURLSearchParams');
module.exports = typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;
import AxiosURLSearchParams from '../../../helpers/AxiosURLSearchParams.js';
export default typeof URLSearchParams !== 'undefined' ? URLSearchParams : AxiosURLSearchParams;

View File

@ -1,11 +1,12 @@
'use strict';
import URLSearchParams from './classes/URLSearchParams.js'
import FormData from './classes/FormData.js'
module.exports = {
export default {
isBrowser: true,
classes: {
URLSearchParams: require('./classes/URLSearchParams'),
FormData: require('./classes/FormData'),
Blob: Blob
URLSearchParams,
FormData,
Blob
},
protocols: ['http', 'https', 'file', 'blob', 'url']
};

View File

@ -1,3 +1,3 @@
'use strict';
import platform from './node/index.js';
module.exports = require('./node/');
export {platform as default}

View File

@ -1,3 +1,3 @@
'use strict';
import FormData from 'form-data';
module.exports = require('form-data');
export default FormData;

View File

@ -1,5 +1,4 @@
'use strict';
var url = require('url');
module.exports = url.URLSearchParams;
import url from 'url';
export default url.URLSearchParams;

View File

@ -1,10 +1,11 @@
'use strict';
import URLSearchParams from './classes/URLSearchParams.js'
import FormData from './classes/FormData.js'
module.exports = {
export default {
isNode: true,
classes: {
URLSearchParams: require('./classes/URLSearchParams'),
FormData: require('./classes/FormData'),
URLSearchParams,
FormData,
Blob: typeof Blob !== 'undefined' && Blob || null
},
protocols: [ 'http', 'https', 'file', 'data' ]

View File

@ -1,16 +1,16 @@
'use strict';
var bind = require('./helpers/bind');
import bind from './helpers/bind.js';
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
const toString = Object.prototype.toString;
// eslint-disable-next-line func-names
var kindOf = (function(cache) {
const kindOf = (cache => {
// eslint-disable-next-line func-names
return function(thing) {
var str = toString.call(thing);
return thing => {
const str = toString.call(thing);
return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());
};
})(Object.create(null));
@ -22,6 +22,12 @@ function kindOfTest(type) {
};
}
function typeOfTest(type) {
return thing => {
return typeof thing === type;
};
}
/**
* Determine if a value is an Array
*
@ -36,18 +42,16 @@ function isArray(val) {
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
const isUndefined = typeOfTest('undefined');
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Buffer, otherwise false
*/
@ -59,22 +63,22 @@ function isBuffer(val) {
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
var isArrayBuffer = kindOfTest('ArrayBuffer');
const isArrayBuffer = kindOfTest('ArrayBuffer');
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
let result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
@ -86,40 +90,54 @@ function isArrayBufferView(val) {
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
const isString = typeOfTest('string');
/**
* Determine if a value is a Function
*
* @param {*} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
const isFunction = typeOfTest('function');
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
const isNumber = typeOfTest('number');
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
function isObject(thing) {
return thing !== null && typeof thing === 'object';
}
/**
* Determine if a value is a Boolean
*
* @param {*} thing The value to test
* @returns {boolean} True if value is a Boolean, otherwise false
*/
const isBoolean = thing => {
return thing === true || thing === false;
};
/**
* Determine if a value is a plain Object
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a plain Object, otherwise false
*/
@ -128,61 +146,50 @@ function isPlainObject(val) {
return false;
}
var prototype = Object.getPrototypeOf(val);
const prototype = Object.getPrototypeOf(val);
return prototype === null || prototype === Object.prototype;
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Date, otherwise false
*/
var isDate = kindOfTest('Date');
const isDate = kindOfTest('Date');
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
var isFile = kindOfTest('File');
const isFile = kindOfTest('File');
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Blob, otherwise false
*/
var isBlob = kindOfTest('Blob');
const isBlob = kindOfTest('Blob');
/**
* Determine if a value is a FileList
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a File, otherwise false
*/
var isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
*
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
const isFileList = kindOfTest('FileList');
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a Stream, otherwise false
*/
@ -193,12 +200,12 @@ function isStream(val) {
/**
* Determine if a value is a FormData
*
* @param {Object} thing The value to test
* @param {*} thing The value to test
*
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(thing) {
var pattern = '[object FormData]';
const pattern = '[object FormData]';
return thing && (
(typeof FormData === 'function' && thing instanceof FormData) ||
toString.call(thing) === pattern ||
@ -209,11 +216,11 @@ function isFormData(thing) {
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @param {*} val The value to test
*
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
var isURLSearchParams = kindOfTest('URLSearchParams');
const isURLSearchParams = kindOfTest('URLSearchParams');
/**
* Trim excess whitespace off the beginning and end of a string
@ -244,7 +251,7 @@ function trim(str) {
* @returns {boolean}
*/
function isStandardBrowserEnv() {
var product;
let product;
if (typeof navigator !== 'undefined' && (
(product = navigator.product) === 'ReactNative' ||
product === 'NativeScript' ||
@ -268,14 +275,18 @@ function isStandardBrowserEnv() {
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*
* @param {Boolean} [allOwnKeys = false]
* @returns {void}
*/
function forEach(obj, fn) {
function forEach(obj, fn, {allOwnKeys = false} = {}) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
let i;
let l;
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
@ -284,15 +295,18 @@ function forEach(obj, fn) {
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
for (i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);
const len = keys.length;
let key;
for (i = 0; i < len; i++) {
key = keys[i];
fn.call(null, obj[key], key, obj);
}
}
}
@ -316,7 +330,7 @@ function forEach(obj, fn) {
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
const result = {};
function assignValue(val, key) {
if (isPlainObject(result[key]) && isPlainObject(val)) {
result[key] = merge(result[key], val);
@ -329,8 +343,8 @@ function merge(/* obj1, obj2, obj3, ... */) {
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
for (let i = 0, l = arguments.length; i < l; i++) {
arguments[i] && forEach(arguments[i], assignValue);
}
return result;
}
@ -342,16 +356,17 @@ function merge(/* obj1, obj2, obj3, ... */) {
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
*
* @param {Boolean} [allOwnKeys]
* @returns {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
function extend(a, b, thisArg, {allOwnKeys}= {}) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
}, {allOwnKeys});
return a;
}
@ -381,6 +396,9 @@ function stripBOM(content) {
function inherits(constructor, superConstructor, props, descriptors) {
constructor.prototype = Object.create(superConstructor.prototype, descriptors);
constructor.prototype.constructor = constructor;
Object.defineProperty(constructor, 'super', {
value: superConstructor.prototype
});
props && Object.assign(constructor.prototype, props);
}
@ -394,10 +412,10 @@ function inherits(constructor, superConstructor, props, descriptors) {
* @returns {Object}
*/
function toFlatObject(sourceObj, destObj, filter, propFilter) {
var props;
var i;
var prop;
var merged = {};
let props;
let i;
let prop;
const merged = {};
destObj = destObj || {};
// eslint-disable-next-line no-eq-null,eqeqeq
@ -434,7 +452,7 @@ function endsWith(str, searchString, position) {
position = str.length;
}
position -= searchString.length;
var lastIndex = str.indexOf(searchString, position);
const lastIndex = str.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
@ -449,9 +467,9 @@ function endsWith(str, searchString, position) {
function toArray(thing) {
if (!thing) return null;
if (isArray(thing)) return thing;
var i = thing.length;
let i = thing.length;
if (!isNumber(i)) return null;
var arr = new Array(i);
const arr = new Array(i);
while (i-- > 0) {
arr[i] = thing[i];
}
@ -467,9 +485,9 @@ function toArray(thing) {
* @returns {Array}
*/
// eslint-disable-next-line func-names
var isTypedArray = (function(TypedArray) {
const isTypedArray = (TypedArray => {
// eslint-disable-next-line func-names
return function(thing) {
return thing => {
return TypedArray && thing instanceof TypedArray;
};
})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));
@ -483,14 +501,14 @@ var isTypedArray = (function(TypedArray) {
* @returns {void}
*/
function forEachEntry(obj, fn) {
var generator = obj && obj[Symbol.iterator];
const generator = obj && obj[Symbol.iterator];
var iterator = generator.call(obj);
const iterator = generator.call(obj);
var result;
let result;
while ((result = iterator.next()) && !result.done) {
var pair = result.value;
const pair = result.value;
fn.call(obj, pair[0], pair[1]);
}
}
@ -504,8 +522,8 @@ function forEachEntry(obj, fn) {
* @returns {Array<boolean>}
*/
function matchAll(regExp, str) {
var matches;
var arr = [];
let matches;
const arr = [];
while ((matches = regExp.exec(str)) !== null) {
arr.push(matches);
@ -515,48 +533,134 @@ function matchAll(regExp, str) {
}
/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */
var isHTMLForm = kindOfTest('HTMLFormElement');
const isHTMLForm = kindOfTest('HTMLFormElement');
const toCamelCase = str => {
return str.toLowerCase().replace(/[_-\s]([a-z\d])(\w*)/g,
function replacer(m, p1, p2) {
return p1.toUpperCase() + p2;
}
);
};
/* Creating a function that will check if an object has a property. */
var hasOwnProperty = (function resolver(_hasOwnProperty) {
return function(obj, prop) {
const hasOwnProperty = (function resolver(_hasOwnProperty) {
return (obj, prop) => {
return _hasOwnProperty.call(obj, prop);
};
})(Object.prototype.hasOwnProperty);
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isPlainObject: isPlainObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
extend: extend,
trim: trim,
stripBOM: stripBOM,
inherits: inherits,
toFlatObject: toFlatObject,
kindOf: kindOf,
kindOfTest: kindOfTest,
endsWith: endsWith,
toArray: toArray,
isTypedArray: isTypedArray,
isFileList: isFileList,
forEachEntry: forEachEntry,
matchAll: matchAll,
isHTMLForm: isHTMLForm,
hasOwnProperty: hasOwnProperty
/**
* Determine if a value is a RegExp object
*
* @param {*} val The value to test
*
* @returns {boolean} True if value is a RegExp object, otherwise false
*/
const isRegExp = kindOfTest('RegExp');
function reduceDescriptors(obj, reducer) {
const descriptors = Object.getOwnPropertyDescriptors(obj);
const reducedDescriptors = {};
forEach(descriptors, (descriptor, name) => {
if (reducer(descriptor, name, obj) !== false) {
reducedDescriptors[name] = descriptor;
}
});
Object.defineProperties(obj, reducedDescriptors);
}
/**
* Makes all methods read-only
* @param {Object} obj
*/
function freezeMethods(obj) {
reduceDescriptors(obj, (descriptor, name) => {
const value = obj[name];
if (!isFunction(value)) return;
descriptor.enumerable = false;
if ('writable' in descriptor) {
descriptor.writable = false;
return;
}
if (!descriptor.set) {
descriptor.set = () => {
throw Error('Can not read-only method \'' + name + '\'');
};
}
});
}
function toObjectSet(arrayOrString, delimiter) {
const obj = {};
function define(arr) {
arr.forEach(value => {
obj[value] = true;
});
}
isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));
return obj;
}
function noop() {}
function toFiniteNumber(value, defaultValue) {
value = +value;
return Number.isFinite(value) ? value : defaultValue;
}
export default {
isArray,
isArrayBuffer,
isBuffer,
isFormData,
isArrayBufferView,
isString,
isNumber,
isBoolean,
isObject,
isPlainObject,
isUndefined,
isDate,
isFile,
isBlob,
isRegExp,
isFunction,
isStream,
isURLSearchParams,
isTypedArray,
isFileList,
isStandardBrowserEnv,
forEach,
merge,
extend,
trim,
stripBOM,
inherits,
toFlatObject,
kindOf,
kindOfTest,
endsWith,
toArray,
forEachEntry,
matchAll,
isHTMLForm,
hasOwnProperty,
hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors,
freezeMethods,
toObjectSet,
toCamelCase,
noop,
toFiniteNumber
};

12308
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -3,12 +3,33 @@
"version": "1.0.0-alpha.1",
"description": "Promise based HTTP client for the browser and node.js",
"main": "index.js",
"exports": {
".": {
"browser": {
"require": "./index.js",
"default": "./index.js"
},
"default": {
"require": "./dist/node/axios.cjs",
"default": "./index.js"
}
}
},
"type": "module",
"types": "index.d.ts",
"scripts": {
"test": "node bin/ssl_hotfix.js grunt test && node bin/ssl_hotfix.js dtslint",
"test": "npm run test:eslint && npm run test:mocha && npm run test:karma && npm run test:dtslint",
"test:eslint": "node bin/ssl_hotfix.js eslint lib/**/*.js",
"test:dtslint": "node bin/ssl_hotfix.js dtslint",
"test:mocha": "node bin/ssl_hotfix.js mocha test/unit/**/*.js --timeout 30000 --exit",
"test:karma": "node bin/ssl_hotfix.js cross-env LISTEN_ADDR=:: karma start karma.conf.cjs --single-run",
"test:karma:server": "node bin/ssl_hotfix.js cross-env karma start karma.conf.cjs",
"start": "node ./sandbox/server.js",
"preversion": "grunt version && npm test",
"build": "cross-env NODE_ENV=production grunt build",
"preversion": "gulp version && npm test",
"version": "npm run build && git add dist && git add package.json",
"prepublishOnly": "npm test",
"postpublish": "git push && git push --tags ",
"build": "gulp clear && cross-env NODE_ENV=production rollup -c -m",
"examples": "node ./examples/server.js",
"coveralls": "cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js",
"fix": "eslint --fix lib/**/*.js"
@ -31,7 +52,8 @@
},
"homepage": "https://axios-http.com",
"devDependencies": {
"@rollup/plugin-babel": "^5.3.0",
"@babel/preset-env": "^7.18.2",
"@rollup/plugin-babel": "^5.3.1",
"@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-multi-entry": "^4.0.0",
@ -40,20 +62,15 @@
"body-parser": "^1.20.0",
"coveralls": "^3.1.1",
"cross-env": "^7.0.3",
"dev-null": "^0.1.1",
"dtslint": "^4.2.1",
"es6-promise": "^4.2.8",
"eslint": "^8.17.0",
"express": "^4.18.1",
"formidable": "^2.0.1",
"grunt": "^1.4.1",
"grunt-banner": "^0.6.0",
"grunt-cli": "^1.4.3",
"grunt-contrib-clean": "^2.0.0",
"grunt-contrib-watch": "^1.1.0",
"grunt-eslint": "^24.0.0",
"grunt-karma": "^4.0.2",
"grunt-mocha-test": "^0.13.3",
"grunt-shell": "^3.0.1",
"grunt-webpack": "^5.0.0",
"fs-extra": "^10.1.0",
"get-stream": "^3.0.0",
"gulp": "^4.0.2",
"istanbul-instrumenter-loader": "^3.0.1",
"jasmine-core": "^2.4.1",
"karma": "^6.3.17",
@ -61,23 +78,22 @@
"karma-firefox-launcher": "^2.1.2",
"karma-jasmine": "^1.1.1",
"karma-jasmine-ajax": "^0.1.13",
"karma-rollup-preprocessor": "^7.0.8",
"karma-safari-launcher": "^1.0.0",
"karma-sauce-launcher": "^4.3.6",
"karma-sinon": "^1.0.5",
"karma-sourcemap-loader": "^0.3.8",
"karma-webpack": "^4.0.2",
"load-grunt-tasks": "^5.1.0",
"minimist": "^1.2.6",
"mocha": "^8.2.1",
"mocha": "^10.0.0",
"multer": "^1.4.4",
"rollup": "^2.67.0",
"rollup-plugin-auto-external": "^2.0.0",
"rollup-plugin-terser": "^7.0.2",
"sinon": "^4.5.0",
"stream-throttle": "^0.1.3",
"terser-webpack-plugin": "^4.2.3",
"typescript": "^4.6.3",
"url-search-params": "^0.10.0",
"webpack": "^4.44.2",
"webpack-dev-server": "^3.11.0"
"url-search-params": "^0.10.0"
},
"browser": {
"./lib/adapters/http.js": "./lib/adapters/xhr.js",
@ -96,5 +112,21 @@
"path": "./dist/axios.min.js",
"threshold": "5kB"
}
],
"contributors": [
"Matt Zabriskie (https://github.com/mzabriskie)",
"Nick Uraltsev (https://github.com/nickuraltsev)",
"Jay (https://github.com/jasonsaayman)",
"Emily Morehouse (https://github.com/emilyemorehouse)",
"Dmitriy Mozgovoy (https://github.com/DigitalBrainJS)",
"Rubén Norte (https://github.com/rubennorte)",
"Justin Beckwith (https://github.com/JustinBeckwith)",
"Martti Laine (https://github.com/codeclown)",
"Xianming Zhong (https://github.com/chinesedfan)",
"Rikki Gibson (https://github.com/RikkiGibson)",
"Remco Haszing (https://github.com/remcohaszing)",
"Yasu Flores (https://github.com/yasuf)",
"Ben Carp (https://github.com/carpben)",
"Daniel Lopretto (https://github.com/timemachine3030)"
]
}
}

View File

@ -2,13 +2,15 @@ import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import {terser} from "rollup-plugin-terser";
import json from '@rollup/plugin-json';
import { babel } from '@rollup/plugin-babel';
import autoExternal from 'rollup-plugin-auto-external';
const lib = require("./package.json");
const outputFileName = 'axios';
const name = "axios";
const input = './lib/axios.js';
const buildConfig = (config) => {
const buildConfig = ({es5, browser = true, minifiedVersion = true, ...config}) => {
const build = ({minified}) => ({
input,
@ -19,25 +21,35 @@ const buildConfig = (config) => {
},
plugins: [
json(),
resolve({browser: true}),
resolve({browser}),
commonjs(),
minified && terser(),
...(es5 ? [babel({
babelHelpers: 'bundled',
presets: ['@babel/preset-env']
})] : []),
...(config.plugins || []),
]
});
return [
const configs = [
build({minified: false}),
build({minified: true}),
];
if (minifiedVersion) {
build({minified: true})
}
return configs;
};
export default async () => {
const year = new Date().getFullYear();
const banner = `// ${lib.name} v${lib.version} Copyright (c) ${year} ${lib.author}`;
const banner = `// Axios v${lib.version} Copyright (c) ${year} ${lib.author} and contributors`;
return [
...buildConfig({
es5: true,
output: {
file: `dist/${outputFileName}`,
name,
@ -55,6 +67,22 @@ export default async () => {
exports: "named",
banner
}
})
}),
// Node.js commonjs build
{
input,
output: {
file: `dist/node/${name}.cjs`,
format: "cjs",
preferConst: true,
exports: "default",
banner
},
plugins: [
autoExternal(),
resolve(),
commonjs()
]
}
]
};

View File

@ -1,7 +1,7 @@
var axios = require('../index');
import axios from '../index';
var URL = 'http://127.0.0.1:3000/api';
var BODY = {
const URL = 'http://127.0.0.1:3000/api';
const BODY = {
foo: 'bar',
baz: 1234
};

View File

@ -1,8 +1,8 @@
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var server;
import fs from 'fs';
import url from 'url';
import path from 'path';
import http from 'http';
let server;
function pipeFileToResponse(res, file, type) {
if (type) {
@ -17,8 +17,8 @@ function pipeFileToResponse(res, file, type) {
server = http.createServer(function (req, res) {
req.setEncoding('utf8');
var parsed = url.parse(req.url, true);
var pathname = parsed.pathname;
const parsed = url.parse(req.url, true);
let pathname = parsed.pathname;
console.log('[' + new Date() + ']', req.method, pathname);
@ -33,9 +33,9 @@ server = http.createServer(function (req, res) {
} else if (pathname === '/axios.map') {
pipeFileToResponse(res, '../dist/axios.map', 'text/javascript');
} else if (pathname === '/api') {
var status;
var result;
var data = '';
let status;
let result;
let data = '';
req.on('data', function (chunk) {
data += chunk;

24
test/manual/progress.html Normal file
View File

@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
See your console
<script src="../../dist/axios.js"></script>
<script>
const data = new Int8Array(10 * 1024 * 1024);
data.fill(123);
axios.post('http://httpbin.org/post', data, {
onUploadProgress: console.log,
onDownloadProgress: console.log,
}).then(data=> {
console.log(`Done: `, data);
}).catch(console.warn);
</script>
</body>
</html>

View File

@ -1,123 +1,41 @@
// Polyfill ES6 Promise
require('es6-promise').polyfill();
import _axios from '../../index.js';
// Polyfill URLSearchParams
URLSearchParams = require('url-search-params');
// Import axios
axios = require('../../index');
window.axios = _axios;
// Jasmine config
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
jasmine.getEnv().defaultTimeoutInterval = 20000;
// Get Ajax request using an increasing timeout to retry
getAjaxRequest = (function () {
var attempts = 0;
var MAX_ATTEMPTS = 5;
var ATTEMPT_DELAY_FACTOR = 5;
window.getAjaxRequest = (function () {
let attempts = 0;
const MAX_ATTEMPTS = 5;
const ATTEMPT_DELAY_FACTOR = 5;
function getAjaxRequest() {
return new Promise(function (resolve, reject) {
attempts = 0;
attemptGettingAjaxRequest(resolve, reject);
});
}
function attemptGettingAjaxRequest(resolve, reject) {
var delay = attempts * attempts * ATTEMPT_DELAY_FACTOR;
if (attempts++ > MAX_ATTEMPTS) {
reject(new Error('No request was found'));
return;
function getAjaxRequest() {
return new Promise(function (resolve, reject) {
attempts = 0;
attemptGettingAjaxRequest(resolve, reject);
});
}
setTimeout(function () {
var request = jasmine.Ajax.requests.mostRecent();
if (request) {
resolve(request);
} else {
attemptGettingAjaxRequest(resolve, reject);
function attemptGettingAjaxRequest(resolve, reject) {
const delay = attempts * attempts * ATTEMPT_DELAY_FACTOR;
if (attempts++ > MAX_ATTEMPTS) {
reject(new Error('No request was found'));
return;
}
}, delay);
}
return getAjaxRequest;
setTimeout(function () {
const request = jasmine.Ajax.requests.mostRecent();
if (request) {
resolve(request);
} else {
attemptGettingAjaxRequest(resolve, reject);
}
}, delay);
}
return getAjaxRequest;
})();
// Validate an invalid character error
validateInvalidCharacterError = function validateInvalidCharacterError(error) {
expect(/character/i.test(error.message)).toEqual(true);
};
// Setup basic auth tests
setupBasicAuthTest = function setupBasicAuthTest() {
beforeEach(function () {
jasmine.Ajax.install();
});
afterEach(function () {
jasmine.Ajax.uninstall();
});
it('should accept HTTP Basic auth with username/password', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin',
password: 'open sesame'
}
});
setTimeout(function () {
var request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
done();
}, 100);
});
it('should accept HTTP Basic auth credentials without the password parameter', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin'
}
});
setTimeout(function () {
var request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjo=');
done();
}, 100);
});
it('should accept HTTP Basic auth credentials with non-Latin1 characters in password', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin',
password: 'open ßç£☃sesame'
}
});
setTimeout(function () {
var request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ==');
done();
}, 100);
});
it('should fail to encode HTTP Basic auth credentials with non-Latin1 characters in username', function (done) {
axios('/foo', {
auth: {
username: 'Aladßç£☃din',
password: 'open sesame'
}
}).then(function(response) {
done(new Error('Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.'));
}).catch(function(error) {
validateInvalidCharacterError(error);
done();
});
});
};

View File

@ -1,4 +1,3 @@
var axios = require('../../index');
describe('adapter', function () {
beforeEach(function () {
@ -13,7 +12,7 @@ describe('adapter', function () {
axios('/foo', {
adapter: function barAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve) {
var request = new XMLHttpRequest();
const request = new XMLHttpRequest();
request.open('GET', '/bar');
request.onreadystatechange = function () {
@ -26,7 +25,7 @@ describe('adapter', function () {
request.send(null);
});
}
}).catch(console.log);
}).catch(done);
getAjaxRequest().then(function(request) {
expect(request.url).toBe('/bar');
@ -35,11 +34,11 @@ describe('adapter', function () {
});
it('should execute adapter code synchronously', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios('/foo', {
adapter: function barAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve) {
var request = new XMLHttpRequest();
const request = new XMLHttpRequest();
request.open('GET', '/bar');
request.onreadystatechange = function () {
@ -53,7 +52,7 @@ describe('adapter', function () {
request.send(null);
});
}
}).catch(console.log);
}).catch(done);
asyncFlag = true;
@ -63,7 +62,7 @@ describe('adapter', function () {
});
it('should execute adapter code asynchronously when interceptor is present', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios.interceptors.request.use(function (config) {
config.headers.async = 'async it!';
@ -73,7 +72,7 @@ describe('adapter', function () {
axios('/foo', {
adapter: function barAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve) {
var request = new XMLHttpRequest();
const request = new XMLHttpRequest();
request.open('GET', '/bar');
request.onreadystatechange = function () {
@ -87,7 +86,7 @@ describe('adapter', function () {
request.send(null);
});
}
}).catch(console.log);
}).catch(done);
asyncFlag = true;

View File

@ -1,3 +1,4 @@
describe('static api', function () {
it('should have request method helpers', function () {
expect(typeof axios.request).toEqual('function');
@ -11,7 +12,7 @@ describe('static api', function () {
});
it('should have promise method helpers', function () {
var promise = axios('/test');
const promise = axios('/test');
expect(typeof promise.then).toEqual('function');
expect(typeof promise.catch).toEqual('function');
@ -52,7 +53,7 @@ describe('static api', function () {
});
describe('instance api', function () {
var instance = axios.create();
const instance = axios.create();
it('should have request methods', function () {
expect(typeof instance.request).toEqual('function');

View File

@ -1,3 +1,77 @@
import axios from "../../index";
function validateInvalidCharacterError(error) {
expect(/character/i.test(error.message)).toEqual(true);
};
describe('basicAuth', function () {
setupBasicAuthTest();
// Validate an invalid character error
beforeEach(function () {
jasmine.Ajax.install();
});
afterEach(function () {
jasmine.Ajax.uninstall();
});
it('should accept HTTP Basic auth with username/password', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin',
password: 'open sesame'
}
});
setTimeout(function () {
const request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==');
done();
}, 100);
});
it('should accept HTTP Basic auth credentials without the password parameter', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin'
}
});
setTimeout(function () {
const request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjo=');
done();
}, 100);
});
it('should accept HTTP Basic auth credentials with non-Latin1 characters in password', function (done) {
axios('/foo', {
auth: {
username: 'Aladdin',
password: 'open ßç£☃sesame'
}
});
setTimeout(function () {
const request = jasmine.Ajax.requests.mostRecent();
expect(request.requestHeaders['Authorization']).toEqual('Basic QWxhZGRpbjpvcGVuIMOfw6fCo+KYg3Nlc2FtZQ==');
done();
}, 100);
});
it('should fail to encode HTTP Basic auth credentials with non-Latin1 characters in username', function (done) {
axios('/foo', {
auth: {
username: 'Aladßç£☃din',
password: 'open sesame'
}
}).then(function (response) {
done(new Error('Should not succeed to make a HTTP Basic auth request with non-latin1 chars in credentials.'));
}).catch(function (error) {
validateInvalidCharacterError(error);
done();
});
});
});

View File

@ -1,8 +1,8 @@
var Cancel = axios.Cancel;
var CancelToken = axios.CancelToken;
var _AbortController = require('abortcontroller-polyfill/dist/cjs-ponyfill.js').AbortController;
const Cancel = axios.Cancel;
const CancelToken = axios.CancelToken;
import {AbortController as _AbortController} from 'abortcontroller-polyfill/dist/cjs-ponyfill.js';
var AbortController = typeof AbortController === 'function' ? AbortController : _AbortController;
const envAbortController = typeof AbortController === 'function' ? AbortController : _AbortController;
describe('cancel', function() {
beforeEach(function() {
@ -15,7 +15,7 @@ describe('cancel', function() {
describe('when called before sending request', function() {
it('rejects Promise with a CanceledError object', function(done) {
var source = CancelToken.source();
const source = CancelToken.source();
source.cancel('Operation has been canceled.');
axios.get('/foo', {
cancelToken: source.token
@ -29,7 +29,7 @@ describe('cancel', function() {
describe('when called after request has been sent', function() {
it('rejects Promise with a CanceledError object', function(done) {
var source = CancelToken.source();
const source = CancelToken.source();
axios.get('/foo/bar', {
cancelToken: source.token
}).catch(function(thrown) {
@ -49,8 +49,8 @@ describe('cancel', function() {
});
it('calls abort on request object', function(done) {
var source = CancelToken.source();
var request;
const source = CancelToken.source();
let request;
axios.get('/foo/bar', {
cancelToken: source.token
}).catch(function() {
@ -91,7 +91,7 @@ describe('cancel', function() {
// });
it('it should support cancellation using AbortController signal', function(done) {
var controller = new AbortController();
const controller = new envAbortController();
axios.get('/foo/bar', {
signal: controller.signal

View File

@ -1,5 +1,5 @@
var CancelToken = require('../../../lib/cancel/CancelToken');
var CanceledError = require('../../../lib/cancel/CanceledError');
import CancelToken from '../../../lib/cancel/CancelToken';
import CanceledError from '../../../lib/cancel/CanceledError';
describe('CancelToken', function() {
describe('constructor', function() {
@ -18,8 +18,8 @@ describe('CancelToken', function() {
describe('reason', function() {
it('returns a CanceledError if cancellation has been requested', function() {
var cancel;
var token = new CancelToken(function(c) {
let cancel;
const token = new CancelToken(function(c) {
cancel = c;
});
cancel('Operation has been canceled.');
@ -28,15 +28,15 @@ describe('CancelToken', function() {
});
it('returns undefined if cancellation has not been requested', function() {
var token = new CancelToken(function() {});
const token = new CancelToken(function() {});
expect(token.reason).toBeUndefined();
});
});
describe('promise', function() {
it('returns a Promise that resolves when cancellation is requested', function(done) {
var cancel;
var token = new CancelToken(function(c) {
let cancel;
const token = new CancelToken(function(c) {
cancel = c;
});
token.promise.then(function onFulfilled(value) {
@ -51,8 +51,8 @@ describe('CancelToken', function() {
describe('throwIfRequested', function() {
it('throws if cancellation has been requested', function() {
// Note: we cannot use expect.toThrowError here as CanceledError does not inherit from Error
var cancel;
var token = new CancelToken(function(c) {
let cancel;
const token = new CancelToken(function(c) {
cancel = c;
});
cancel('Operation has been canceled.');
@ -68,14 +68,14 @@ describe('CancelToken', function() {
});
it('does not throw if cancellation has not been requested', function() {
var token = new CancelToken(function() {});
const token = new CancelToken(function() {});
token.throwIfRequested();
});
});
describe('source', function() {
it('returns an object containing token and cancel function', function() {
var source = CancelToken.source();
const source = CancelToken.source();
expect(source.token).toEqual(jasmine.any(CancelToken));
expect(source.cancel).toEqual(jasmine.any(Function));
expect(source.token.reason).toBeUndefined();

View File

@ -1,14 +1,14 @@
var CanceledError = require('../../../lib/cancel/CanceledError');
import CanceledError from '../../../lib/cancel/CanceledError';
describe('Cancel', function() {
describe('toString', function() {
it('returns correct result when message is not specified', function() {
var cancel = new CanceledError();
const cancel = new CanceledError();
expect(cancel.toString()).toBe('CanceledError: canceled');
});
it('returns correct result when message is specified', function() {
var cancel = new CanceledError('Operation has been canceled.');
const cancel = new CanceledError('Operation has been canceled.');
expect(cancel.toString()).toBe('CanceledError: Operation has been canceled.');
});
});

View File

@ -1,5 +1,5 @@
var isCancel = require('../../../lib/cancel/isCancel');
var CanceledError = require('../../../lib/cancel/CanceledError');
import isCancel from '../../../lib/cancel/isCancel';
import CanceledError from '../../../lib/cancel/CanceledError';
describe('isCancel', function() {
it('returns true if value is a CanceledError', function() {

View File

@ -1,10 +1,10 @@
var AxiosError = require('../../../lib/core/AxiosError');
import AxiosError from '../../../lib/core/AxiosError';
describe('core::AxiosError', function() {
it('should create an Error with message, config, code, request, response, stack and isAxiosError', function() {
var request = { path: '/foo' };
var response = { status: 200, data: { foo: 'bar' } };
var error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
const request = { path: '/foo' };
const response = { status: 200, data: { foo: 'bar' } };
const error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
expect(error instanceof Error).toBe(true);
expect(error.message).toBe('Boom!');
expect(error.config).toEqual({ foo: 'bar' });
@ -17,10 +17,10 @@ describe('core::AxiosError', function() {
it('should create an Error that can be serialized to JSON', function() {
// Attempting to serialize request and response results in
// TypeError: Converting circular structure to JSON
var request = { path: '/foo' };
var response = { status: 200, data: { foo: 'bar' } };
var error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
var json = error.toJSON();
const request = { path: '/foo' };
const response = { status: 200, data: { foo: 'bar' } };
const error = new AxiosError('Boom!', 'ESOMETHING', { foo: 'bar' }, request, response);
const json = error.toJSON();
expect(json.message).toBe('Boom!');
expect(json.config).toEqual({ foo: 'bar' });
expect(json.code).toBe('ESOMETHING');
@ -31,11 +31,11 @@ describe('core::AxiosError', function() {
describe('core::createError.from', function() {
it('should add config, config, request and response to error', function() {
var error = new Error('Boom!');
var request = { path: '/foo' };
var response = { status: 200, data: { foo: 'bar' } };
const error = new Error('Boom!');
const request = { path: '/foo' };
const response = { status: 200, data: { foo: 'bar' } };
var axiosError = AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }, request, response);
const axiosError = AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }, request, response);
expect(axiosError.config).toEqual({ foo: 'bar' });
expect(axiosError.code).toBe('ESOMETHING');
expect(axiosError.request).toBe(request);
@ -44,7 +44,7 @@ describe('core::AxiosError', function() {
});
it('should return error', function() {
var error = new Error('Boom!');
const error = new Error('Boom!');
expect(AxiosError.from(error, 'ESOMETHING', { foo: 'bar' }) instanceof AxiosError).toBeTruthy();
});
});

View File

@ -1,4 +1,4 @@
var buildFullPath = require('../../../lib/core/buildFullPath');
import buildFullPath from '../../../lib/core/buildFullPath';
describe('helpers::buildFullPath', function () {
it('should combine URLs when the requestedURL is relative', function () {

View File

@ -1,5 +1,5 @@
var defaults = require('../../../lib/defaults');
var mergeConfig = require('../../../lib/core/mergeConfig');
import defaults from '../../../lib/defaults';
import mergeConfig from '../../../lib/core/mergeConfig';
describe('core::mergeConfig', function() {
it('should accept undefined for second argument', function() {
@ -11,19 +11,19 @@ describe('core::mergeConfig', function() {
});
it('should not leave references', function() {
var merged = mergeConfig(defaults, {});
const merged = mergeConfig(defaults, {});
expect(merged).not.toBe(defaults);
expect(merged.headers).not.toBe(defaults.headers);
});
it('should allow setting request options', function() {
var config = {
const config = {
url: '__sample url__',
method: '__sample method__',
params: '__sample params__',
data: { foo: true }
};
var merged = mergeConfig(defaults, config);
const merged = mergeConfig(defaults, config);
expect(merged.url).toEqual(config.url);
expect(merged.method).toEqual(config.method);
expect(merged.params).toEqual(config.params);
@ -31,18 +31,18 @@ describe('core::mergeConfig', function() {
});
it('should not inherit request options', function() {
var localDefaults = {
const localDefaults = {
method: '__sample method__',
data: { foo: true }
};
var merged = mergeConfig(localDefaults, {});
const merged = mergeConfig(localDefaults, {});
expect(merged.method).toEqual(undefined);
expect(merged.data).toEqual(undefined);
});
['auth', 'headers', 'params', 'proxy'].forEach(function(key) {
it('should set new config for' + key + ' without default', function() {
var a = {}, b = {}, c = {}
const a = {}, b = {}, c = {};
a[key] = undefined
b[key] = { user: 'foo', pass: 'test' }
c[key] = { user: 'foo', pass: 'test' }
@ -51,7 +51,7 @@ describe('core::mergeConfig', function() {
});
it('should merge ' + key + ' with defaults', function() {
var a = {}, b = {}, c = {};
const a = {}, b = {}, c = {};
a[key] = { user: 'foo', pass: 'bar' };
b[key] = { pass: 'test' };
c[key] = { user: 'foo', pass: 'test' };
@ -61,7 +61,7 @@ describe('core::mergeConfig', function() {
it('should overwrite default ' + key + ' with a non-object value', function() {
[false, null, 123].forEach(function(value) {
var a = {}, b = {}, c = {};
const a = {}, b = {}, c = {};
a[key] = { user: 'foo', pass: 'test' };
b[key] = value;
c[key] = value;
@ -72,22 +72,22 @@ describe('core::mergeConfig', function() {
});
it('should allow setting other options', function() {
var merged = mergeConfig(defaults, { timeout: 123 });
const merged = mergeConfig(defaults, { timeout: 123 });
expect(merged.timeout).toEqual(123);
});
it('should allow setting custom options', function() {
var merged = mergeConfig(defaults, { foo: 'bar' });
const merged = mergeConfig(defaults, { foo: 'bar' });
expect(merged.foo).toEqual('bar');
});
it('should allow setting custom default options', function() {
var merged = mergeConfig({ foo: 'bar' }, {});
const merged = mergeConfig({ foo: 'bar' }, {});
expect(merged.foo).toEqual('bar');
});
it('should allow merging custom objects in the config', function() {
var merged = mergeConfig({
const merged = mergeConfig({
nestedConfig: {
propertyOnDefaultConfig: true
}
@ -101,28 +101,28 @@ describe('core::mergeConfig', function() {
});
describe('valueFromConfig2Keys', function() {
var config1 = {url: '/foo', method: 'post', data: {a: 3}};
const config1 = {url: '/foo', method: 'post', data: {a: 3}};
it('should skip if config2 is undefined', function() {
expect(mergeConfig(config1, {})).toEqual({});
});
it('should clone config2 if is plain object', function() {
var data = {a: 1, b: 2};
var merged = mergeConfig(config1, {data: data});
const data = {a: 1, b: 2};
const merged = mergeConfig(config1, {data: data});
expect(merged.data).toEqual(data);
expect(merged.data).not.toBe(data);
});
it('should clone config2 if is array', function() {
var data = [1, 2, 3];
var merged = mergeConfig(config1, {data: data});
const data = [1, 2, 3];
const merged = mergeConfig(config1, {data: data});
expect(merged.data).toEqual(data);
expect(merged.data).not.toBe(data);
});
it('should set as config2 in other cases', function() {
var obj = Object.create({});
const obj = Object.create({});
expect(mergeConfig(config1, {data: 1}).data).toBe(1);
expect(mergeConfig(config1, {data: 'str'}).data).toBe('str');
expect(mergeConfig(config1, {data: obj}).data).toBe(obj);
@ -141,24 +141,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config2 if is plain object', function() {
var config1 = {headers: [1, 2, 3]};
var config2 = {headers: {a: 1, b: 2}};
var merged = mergeConfig(config1, config2);
const config1 = {headers: [1, 2, 3]};
const config2 = {headers: {a: 1, b: 2}};
const merged = mergeConfig(config1, config2);
expect(merged.headers).toEqual(config2.headers);
expect(merged.headers).not.toBe(config2.headers);
});
it('should clone config2 if is array', function() {
var config1 = {headers: {a: 1, b: 1}};
var config2 = {headers: [1, 2, 3]};
var merged = mergeConfig(config1, config2);
const config1 = {headers: {a: 1, b: 1}};
const config2 = {headers: [1, 2, 3]};
const merged = mergeConfig(config1, config2);
expect(merged.headers).toEqual(config2.headers);
expect(merged.headers).not.toBe(config2.headers);
});
it('should set as config2 in other cases', function() {
var config1 = {headers: {a: 1, b: 1}};
var obj = Object.create({});
const config1 = {headers: {a: 1, b: 1}};
const obj = Object.create({});
expect(mergeConfig(config1, {headers: 1}).headers).toBe(1);
expect(mergeConfig(config1, {headers: 'str'}).headers).toBe('str');
expect(mergeConfig(config1, {headers: obj}).headers).toBe(obj);
@ -166,24 +166,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config1 if is plain object', function() {
var config1 = {headers: {a: 1, b: 2}};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {headers: {a: 1, b: 2}};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.headers).toEqual(config1.headers);
expect(merged.headers).not.toBe(config1.headers);
});
it('should clone config1 if is array', function() {
var config1 = {headers: [1, 2, 3]};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {headers: [1, 2, 3]};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.headers).toEqual(config1.headers);
expect(merged.headers).not.toBe(config1.headers);
});
it('should set as config1 in other cases', function() {
var config2 = {};
var obj = Object.create({});
const config2 = {};
const obj = Object.create({});
expect(mergeConfig({headers: 1}, config2).headers).toBe(1);
expect(mergeConfig({headers: 'str'}, config2).headers).toBe('str');
expect(mergeConfig({headers: obj}, config2).headers).toBe(obj);
@ -197,24 +197,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config2 if both config1 and config2 are plain object', function() {
var config1 = {transformRequest: {a: 1, b: 1}};
var config2 = {transformRequest: {b: 2, c: 2}};
var merged = mergeConfig(config1, config2);
const config1 = {transformRequest: {a: 1, b: 1}};
const config2 = {transformRequest: {b: 2, c: 2}};
const merged = mergeConfig(config1, config2);
expect(merged.transformRequest).toEqual(config2.transformRequest);
expect(merged.transformRequest).not.toBe(config2.transformRequest);
});
it('should clone config2 if is array', function() {
var config1 = {transformRequest: {a: 1, b: 1}};
var config2 = {transformRequest: [1, 2, 3]};
var merged = mergeConfig(config1, config2);
const config1 = {transformRequest: {a: 1, b: 1}};
const config2 = {transformRequest: [1, 2, 3]};
const merged = mergeConfig(config1, config2);
expect(merged.transformRequest).toEqual(config2.transformRequest);
expect(merged.transformRequest).not.toBe(config2.transformRequest);
});
it('should set as config2 in other cases', function() {
var config1 = {transformRequest: {a: 1, b: 1}};
var obj = Object.create({});
const config1 = {transformRequest: {a: 1, b: 1}};
const obj = Object.create({});
expect(mergeConfig(config1, {transformRequest: 1}).transformRequest).toBe(1);
expect(mergeConfig(config1, {transformRequest: 'str'}).transformRequest).toBe('str');
expect(mergeConfig(config1, {transformRequest: obj}).transformRequest).toBe(obj);
@ -222,24 +222,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config1 if is plain object', function() {
var config1 = {transformRequest: {a: 1, b: 2}};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {transformRequest: {a: 1, b: 2}};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.transformRequest).toEqual(config1.transformRequest);
expect(merged.transformRequest).not.toBe(config1.transformRequest);
});
it('should clone config1 if is array', function() {
var config1 = {transformRequest: [1, 2, 3]};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {transformRequest: [1, 2, 3]};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.transformRequest).toEqual(config1.transformRequest);
expect(merged.transformRequest).not.toBe(config1.transformRequest);
});
it('should set as config1 in other cases', function() {
var config2 = {};
var obj = Object.create({});
const config2 = {};
const obj = Object.create({});
expect(mergeConfig({transformRequest: 1}, config2).transformRequest).toBe(1);
expect(mergeConfig({transformRequest: 'str'}, config2).transformRequest).toBe('str');
expect(mergeConfig({transformRequest: obj}, config2).transformRequest).toBe(obj);
@ -258,24 +258,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config2 if is plain object', function() {
var config1 = {validateStatus: [1, 2, 3]};
var config2 = {validateStatus: {a: 1, b: 2}};
var merged = mergeConfig(config1, config2);
const config1 = {validateStatus: [1, 2, 3]};
const config2 = {validateStatus: {a: 1, b: 2}};
const merged = mergeConfig(config1, config2);
expect(merged.validateStatus).toEqual(config2.validateStatus);
expect(merged.validateStatus).not.toBe(config2.validateStatus);
});
it('should clone config2 if is array', function() {
var config1 = {validateStatus: {a: 1, b: 2}};
var config2 = {validateStatus: [1, 2, 3]};
var merged = mergeConfig(config1, config2);
const config1 = {validateStatus: {a: 1, b: 2}};
const config2 = {validateStatus: [1, 2, 3]};
const merged = mergeConfig(config1, config2);
expect(merged.validateStatus).toEqual(config2.validateStatus);
expect(merged.validateStatus).not.toBe(config2.validateStatus);
});
it('should set as config2 in other cases', function() {
var config1 = {validateStatus: {a: 1, b: 2}};
var obj = Object.create({});
const config1 = {validateStatus: {a: 1, b: 2}};
const obj = Object.create({});
expect(mergeConfig(config1, {validateStatus: 1}).validateStatus).toBe(1);
expect(mergeConfig(config1, {validateStatus: 'str'}).validateStatus).toBe('str');
expect(mergeConfig(config1, {validateStatus: obj}).validateStatus).toBe(obj);
@ -283,24 +283,24 @@ describe('core::mergeConfig', function() {
});
it('should clone config1 if is plain object', function() {
var config1 = {validateStatus: {a: 1, b: 2}};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {validateStatus: {a: 1, b: 2}};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.validateStatus).toEqual(config1.validateStatus);
expect(merged.validateStatus).not.toBe(config1.validateStatus);
});
it('should clone config1 if is array', function() {
var config1 = {validateStatus: [1, 2, 3]};
var config2 = {};
var merged = mergeConfig(config1, config2);
const config1 = {validateStatus: [1, 2, 3]};
const config2 = {};
const merged = mergeConfig(config1, config2);
expect(merged.validateStatus).toEqual(config1.validateStatus);
expect(merged.validateStatus).not.toBe(config1.validateStatus);
});
it('should set as config1 in other cases', function() {
var config2 = {};
var obj = Object.create({});
const config2 = {};
const obj = Object.create({});
expect(mergeConfig({validateStatus: 1}, config2).validateStatus).toBe(1);
expect(mergeConfig({validateStatus: 'str'}, config2).validateStatus).toBe('str');
expect(mergeConfig({validateStatus: obj}, config2).validateStatus).toBe(obj);

View File

@ -1,8 +1,8 @@
var settle = require('../../../lib/core/settle');
import settle from '../../../lib/core/settle';
describe('core::settle', function() {
var resolve;
var reject;
let resolve;
let reject;
beforeEach(function() {
resolve = jasmine.createSpy('resolve');
@ -10,7 +10,7 @@ describe('core::settle', function() {
});
it('should resolve promise if status is not set', function() {
var response = {
const response = {
config: {
validateStatus: function() {
return true;
@ -23,7 +23,7 @@ describe('core::settle', function() {
});
it('should resolve promise if validateStatus is not set', function() {
var response = {
const response = {
status: 500,
config: {
}
@ -34,7 +34,7 @@ describe('core::settle', function() {
});
it('should resolve promise if validateStatus returns true', function() {
var response = {
const response = {
status: 500,
config: {
validateStatus: function() {
@ -48,10 +48,10 @@ describe('core::settle', function() {
});
it('should reject promise if validateStatus returns false', function() {
var req = {
const req = {
path: '/foo'
};
var response = {
const response = {
status: 500,
config: {
validateStatus: function() {
@ -63,7 +63,7 @@ describe('core::settle', function() {
settle(resolve, reject, response);
expect(resolve).not.toHaveBeenCalled();
expect(reject).toHaveBeenCalled();
var reason = reject.calls.first().args[0];
const reason = reject.calls.first().args[0];
expect(reason instanceof Error).toBe(true);
expect(reason.message).toBe('Request failed with status code 500');
expect(reason.config).toBe(response.config);
@ -72,8 +72,8 @@ describe('core::settle', function() {
});
it('should pass status to validateStatus', function() {
var validateStatus = jasmine.createSpy('validateStatus');
var response = {
const validateStatus = jasmine.createSpy('validateStatus');
const response = {
status: 500,
config: {
validateStatus: validateStatus

View File

@ -1,19 +1,22 @@
var transformData = require('../../../lib/core/transformData');
import transformData from '../../../lib/core/transformData';
describe('core::transformData', function () {
it('should support a single transformer', function () {
var data;
data = transformData(data, null, null, function (data) {
let data;
data = transformData.call({
}, function (data) {
data = 'foo';
return data;
});
})
expect(data).toEqual('foo');
});
it('should support an array of transformers', function () {
var data = '';
data = transformData(data, null, null, [function (data) {
let data = '';
data = transformData.call({data}, [function (data) {
data += 'f';
return data;
}, function (data) {
@ -28,11 +31,11 @@ describe('core::transformData', function () {
});
it('should support reference headers in transformData', function () {
var headers = {
const headers = {
'content-type': 'foo/bar',
};
var data = '';
data = transformData(data, headers, null, [function (data, headers) {
let data = '';
data = transformData.call({data, headers}, [function (data, headers) {
data += headers['content-type'];
return data;
}]);
@ -41,11 +44,11 @@ describe('core::transformData', function () {
});
it('should support reference status code in transformData', function () {
var data = '';
data = transformData(data, null, 200, [function (data, headers, status) {
let data = '';
data = transformData.call({}, [function (data, headers, status) {
data += status;
return data;
}]);
}], {data, status: 200});
expect(data).toEqual('200');
});

View File

@ -1,8 +1,9 @@
var defaults = require('../../lib/defaults');
var utils = require('../../lib/utils');
import defaults from '../../lib/defaults';
import utils from '../../lib/utils';
import AxiosHeaders from '../../lib/core/AxiosHeaders';
describe('defaults', function () {
var XSRF_COOKIE_NAME = 'CUSTOM-XSRF-TOKEN';
const XSRF_COOKIE_NAME = 'CUSTOM-XSRF-TOKEN';
beforeEach(function () {
jasmine.Ajax.install();
@ -17,13 +18,13 @@ describe('defaults', function () {
});
it('should transform request json', function () {
expect(defaults.transformRequest[0]({foo: 'bar'})).toEqual('{"foo":"bar"}');
expect(defaults.transformRequest[0]({foo: 'bar'}, new AxiosHeaders())).toEqual('{"foo":"bar"}');
});
it("should also transform request json when 'Content-Type' is 'application/json'", function () {
var headers = {
const headers = new AxiosHeaders({
'Content-Type': 'application/json',
};
});
expect(defaults.transformRequest[0](JSON.stringify({ foo: 'bar' }), headers)).toEqual('{"foo":"bar"}');
expect(defaults.transformRequest[0]([42, 43], headers)).toEqual('[42,43]');
expect(defaults.transformRequest[0]('foo', headers)).toEqual('"foo"');
@ -34,23 +35,23 @@ describe('defaults', function () {
});
it("should transform the plain data object to a FormData instance 'Content-Type' if header is 'multipart/form-data'", function() {
var headers = {
const headers = new AxiosHeaders({
'Content-Type': 'multipart/form-data'
};
});
var payload = {x: 1};
const payload = {x: 1};
var transformed = defaults.transformRequest[0](payload, headers);
const transformed = defaults.transformRequest[0](payload, headers);
expect(transformed).toEqual(jasmine.any(FormData));
});
it('should do nothing to request string', function () {
expect(defaults.transformRequest[0]('foo=bar')).toEqual('foo=bar');
expect(defaults.transformRequest[0]('foo=bar', new AxiosHeaders())).toEqual('foo=bar');
});
it('should transform response json', function () {
var data = defaults.transformResponse[0].call(defaults, '{"foo":"bar"}');
const data = defaults.transformResponse[0].call(defaults, '{"foo":"bar"}');
expect(typeof data).toEqual('object');
expect(data.foo).toEqual('bar');
@ -92,7 +93,7 @@ describe('defaults', function () {
});
it('should use default config for custom instance', function (done) {
var instance = axios.create({
const instance = axios.create({
xsrfCookieName: XSRF_COOKIE_NAME,
xsrfHeaderName: 'X-CUSTOM-XSRF-TOKEN'
});
@ -127,7 +128,7 @@ describe('defaults', function () {
});
it('should use header config', function (done) {
var instance = axios.create({
const instance = axios.create({
headers: {
common: {
'X-COMMON-HEADER': 'commonHeaderValue'
@ -163,7 +164,7 @@ describe('defaults', function () {
it('should be used by custom instance if set before instance created', function (done) {
axios.defaults.baseURL = 'http://example.org/';
var instance = axios.create();
const instance = axios.create();
instance.get('/foo');
@ -174,7 +175,7 @@ describe('defaults', function () {
});
it('should not be used by custom instance if set after instance created', function (done) {
var instance = axios.create();
const instance = axios.create();
axios.defaults.baseURL = 'http://example.org/';
instance.get('/foo');

View File

@ -1,7 +1,7 @@
function testHeaderValue(headers, key, val) {
var found = false;
let found = false;
for (var k in headers) {
for (const k in headers) {
if (k.toLowerCase() === key.toLowerCase()) {
found = true;
expect(headers[k]).toEqual(val);
@ -28,12 +28,12 @@ describe('headers', function () {
});
it('should default common headers', function (done) {
var headers = axios.defaults.headers.common;
const headers = axios.defaults.headers.common;
axios('/foo');
getAjaxRequest().then(function (request) {
for (var key in headers) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
expect(request.requestHeaders[key]).toEqual(headers[key]);
}
@ -43,12 +43,12 @@ describe('headers', function () {
});
it('should add extra headers for post', function (done) {
var headers = axios.defaults.headers.common;
const headers = axios.defaults.headers.common;
axios.post('/foo', 'fizz=buzz');
getAjaxRequest().then(function (request) {
for (var key in headers) {
for (const key in headers) {
if (headers.hasOwnProperty(key)) {
expect(request.requestHeaders[key]).toEqual(headers[key]);
}
@ -72,15 +72,17 @@ describe('headers', function () {
'x-header-a': null,
'x-header-b': undefined
}
}).catch(function (err) {
done(err);
});
getAjaxRequest().then(function (request) {
testHeaderValue(request.requestHeaders, 'Content-Type', null);
testHeaderValue(request.requestHeaders, 'x-header-a', null);
testHeaderValue(request.requestHeaders, 'Content-Type', undefined);
testHeaderValue(request.requestHeaders, 'x-header-a', undefined);
testHeaderValue(request.requestHeaders, 'x-header-b', undefined);
testHeaderValue(request.requestHeaders, 'x-header-c', 'c');
done();
});
}).catch(done);
});
it('should use application/json when posting an object', function (done) {

View File

@ -1,9 +1,9 @@
var bind = require('../../../lib/helpers/bind');
import bind from '../../../lib/helpers/bind';
describe('bind', function () {
it('should bind an object to a function', function () {
var o = { val: 123 };
var f = bind(function (num) {
const o = { val: 123 };
const f = bind(function (num) {
return this.val * num;
}, o);

View File

@ -1,5 +1,5 @@
var buildURL = require('../../../lib/helpers/buildURL');
var URLSearchParams = require('url-search-params');
import buildURL from '../../../lib/helpers/buildURL';
import URLSearchParams from 'url-search-params';
describe('helpers::buildURL', function () {
it('should support null params', function () {
@ -21,7 +21,7 @@ describe('helpers::buildURL', function () {
});
it('should support date params', function () {
var date = new Date();
const date = new Date();
expect(buildURL('/foo', {
date: date

View File

@ -1,4 +1,4 @@
var combineURLs = require('../../../lib/helpers/combineURLs');
import combineURLs from '../../../lib/helpers/combineURLs';
describe('helpers::combineURLs', function () {
it('should combine URLs', function () {

View File

@ -1,9 +1,9 @@
var cookies = require('../../../lib/helpers/cookies');
import cookies from '../../../lib/helpers/cookies';
describe('helpers::cookies', function () {
afterEach(function () {
// Remove all the cookies
var expires = Date.now() - (60 * 60 * 24 * 7);
const expires = Date.now() - (60 * 60 * 24 * 7);
document.cookie.split(';').map(function (cookie) {
return cookie.split('=')[0];
}).forEach(function (name) {

View File

@ -1,4 +1,4 @@
var formDataToJSON = require('../../../lib/helpers/formDataToJSON');
import formDataToJSON from '../../../lib/helpers/formDataToJSON';
describe('formDataToJSON', function () {
it('should convert a FormData Object to JSON Object', function () {

View File

@ -1,4 +1,4 @@
var isAbsoluteURL = require('../../../lib/helpers/isAbsoluteURL');
import isAbsoluteURL from '../../../lib/helpers/isAbsoluteURL';
describe('helpers::isAbsoluteURL', function () {
it('should return true if URL begins with valid scheme name', function () {

View File

@ -1,5 +1,5 @@
var AxiosError = require('../../../lib/core/AxiosError');
var isAxiosError = require('../../../lib/helpers/isAxiosError');
import AxiosError from '../../../lib/core/AxiosError';
import isAxiosError from '../../../lib/helpers/isAxiosError';
describe('helpers::isAxiosError', function() {
it('should return true if the error is created by core::createError', function() {

View File

@ -1,4 +1,4 @@
var isURLSameOrigin = require('../../../lib/helpers/isURLSameOrigin');
import isURLSameOrigin from '../../../lib/helpers/isURLSameOrigin';
describe('helpers::isURLSameOrigin', function () {
it('should detect same origin', function () {

View File

@ -1,21 +0,0 @@
var normalizeHeaderName = require('../../../lib/helpers/normalizeHeaderName');
describe('helpers::normalizeHeaderName', function () {
it('should normalize matching header name', function () {
var headers = {
'conTenT-Type': 'foo/bar',
};
normalizeHeaderName(headers, 'Content-Type');
expect(headers['Content-Type']).toBe('foo/bar');
expect(headers['conTenT-Type']).toBeUndefined();
});
it('should not change non-matching header name', function () {
var headers = {
'content-type': 'foo/bar',
};
normalizeHeaderName(headers, 'Content-Length');
expect(headers['content-type']).toBe('foo/bar');
expect(headers['Content-Length']).toBeUndefined();
});
});

View File

@ -1,9 +1,9 @@
var parseHeaders = require('../../../lib/helpers/parseHeaders');
import parseHeaders from '../../../lib/helpers/parseHeaders';
describe('helpers::parseHeaders', function () {
it('should parse headers', function () {
var date = new Date();
var parsed = parseHeaders(
const date = new Date();
const parsed = parseHeaders(
'Date: ' + date.toISOString() + '\n' +
'Content-Type: application/json\n' +
'Connection: keep-alive\n' +
@ -17,11 +17,11 @@ describe('helpers::parseHeaders', function () {
});
it('should use array for set-cookie', function() {
var parsedZero = parseHeaders('');
var parsedSingle = parseHeaders(
const parsedZero = parseHeaders('');
const parsedSingle = parseHeaders(
'Set-Cookie: key=val;'
);
var parsedMulti = parseHeaders(
const parsedMulti = parseHeaders(
'Set-Cookie: key=val;\n' +
'Set-Cookie: key2=val2;\n'
);
@ -32,7 +32,7 @@ describe('helpers::parseHeaders', function () {
});
it('should handle duplicates', function() {
var parsed = parseHeaders(
const parsed = parseHeaders(
'Age: age-a\n' + // age is in ignore duplicates blocklist
'Age: age-b\n' +
'Foo: foo-a\n' +

View File

@ -1,8 +1,8 @@
var spread = require('../../../lib/helpers/spread');
import spread from '../../../lib/helpers/spread';
describe('helpers::spread', function () {
it('should spread array to arguments', function () {
var value = 0;
let value = 0;
spread(function (a, b) {
value = a * b;
})([5, 10]);
@ -11,7 +11,7 @@ describe('helpers::spread', function () {
});
it('should return callback result', function () {
var value = spread(function (a, b) {
const value = spread(function (a, b) {
return a * b;
})([5, 10]);

View File

@ -1,15 +1,15 @@
var toFormData = require('../../../lib/helpers/toFormData');
import toFormData from '../../../lib/helpers/toFormData';
describe('toFormData', function () {
it('should convert nested data object to FormData with dots option enabled', function () {
var o = {
const o = {
val: 123,
nested: {
arr: ['hello', 'world']
}
};
var form = toFormData(o, null, {dots: true});
const form = toFormData(o, null, {dots: true});
expect(form instanceof FormData).toEqual(true);
expect(Array.from(form.keys()).length).toEqual(3);
expect(form.get('val')).toEqual('123');
@ -17,13 +17,13 @@ describe('toFormData', function () {
});
it('should respect metaTokens option', function () {
var data = {
const data = {
'obj{}': {x: 1, y: 2}
};
var str = JSON.stringify(data['obj{}']);
const str = JSON.stringify(data['obj{}']);
var form = toFormData(data, null, {metaTokens: false});
const form = toFormData(data, null, {metaTokens: false});
expect(Array.from(form.keys()).length).toEqual(1);
expect(form.getAll('obj')).toEqual([str]);
@ -31,12 +31,12 @@ describe('toFormData', function () {
describe('Flat arrays serialization', function () {
it('should include full indexes when the `indexes` option is set to true', function () {
var data = {
const data = {
arr: [1, 2, 3],
arr2: [1, [2], 3]
};
var form = toFormData(data, null, {indexes: true});
const form = toFormData(data, null, {indexes: true});
expect(Array.from(form.keys()).length).toEqual(6);
@ -50,12 +50,12 @@ describe('toFormData', function () {
});
it('should include brackets only when the `indexes` option is set to false', function () {
var data = {
const data = {
arr: [1, 2, 3],
arr2: [1, [2], 3]
};
var form = toFormData(data, null, {indexes: false});
const form = toFormData(data, null, {indexes: false});
expect(Array.from(form.keys()).length).toEqual(6);
@ -67,12 +67,12 @@ describe('toFormData', function () {
});
it('should omit brackets when the `indexes` option is set to null', function () {
var data = {
const data = {
arr: [1, 2, 3],
arr2: [1, [2], 3]
};
var form = toFormData(data, null, {indexes: null});
const form = toFormData(data, null, {indexes: null});
expect(Array.from(form.keys()).length).toEqual(6);
@ -85,14 +85,14 @@ describe('toFormData', function () {
});
it('should convert nested data object to FormData', function () {
var o = {
const o = {
val: 123,
nested: {
arr: ['hello', 'world']
}
};
var form = toFormData(o);
const form = toFormData(o);
expect(form instanceof FormData).toEqual(true);
expect(Array.from(form.keys()).length).toEqual(3);
expect(form.get('val')).toEqual('123');
@ -100,24 +100,24 @@ describe('toFormData', function () {
});
it('should append value whose key ends with [] as separate values with the same key', function () {
var data = {
const data = {
'arr[]': [1, 2, 3]
};
var form = toFormData(data);
const form = toFormData(data);
expect(Array.from(form.keys()).length).toEqual(3);
expect(form.getAll('arr[]')).toEqual(['1', '2', '3']);
});
it('should append value whose key ends with {} as a JSON string', function () {
var data = {
const data = {
'obj{}': {x: 1, y: 2}
};
var str = JSON.stringify(data['obj{}']);
const str = JSON.stringify(data['obj{}']);
var form = toFormData(data);
const form = toFormData(data);
expect(Array.from(form.keys()).length).toEqual(1);
expect(form.getAll('obj{}')).toEqual([str]);

View File

@ -1,6 +1,6 @@
'use strict';
var validator = require('../../../lib/helpers/validator');
import validator from '../../../lib/helpers/validator';
describe('validator::assertOptions', function() {
it('should throw only if unknown an option was passed', function() {

View File

@ -8,9 +8,9 @@ describe('instance', function () {
});
it('should have the same methods as default instance', function () {
var instance = axios.create();
const instance = axios.create();
for (var prop in axios) {
for (const prop in axios) {
if ([
'Axios',
'AxiosError',
@ -35,7 +35,7 @@ describe('instance', function () {
});
it('should make an http request without verb helper', function (done) {
var instance = axios.create();
const instance = axios.create();
instance('/foo');
@ -46,7 +46,7 @@ describe('instance', function () {
});
it('should make an http request with url instead of baseURL', function (done) {
var instance = axios.create({
const instance = axios.create({
url: 'https://api.example.com'
});
@ -59,7 +59,7 @@ describe('instance', function () {
});
it('should make an http request', function (done) {
var instance = axios.create();
const instance = axios.create();
instance.get('/foo');
@ -70,7 +70,7 @@ describe('instance', function () {
});
it('should use instance options', function (done) {
var instance = axios.create({ timeout: 1000 });
const instance = axios.create({ timeout: 1000 });
instance.get('/foo');
@ -81,7 +81,7 @@ describe('instance', function () {
});
it('should have defaults.headers', function () {
var instance = axios.create({
const instance = axios.create({
baseURL: 'https://api.example.com'
});
@ -95,13 +95,13 @@ describe('instance', function () {
return config;
});
var instance = axios.create();
const instance = axios.create();
instance.interceptors.request.use(function (config) {
config.bar = true;
return config;
});
var response;
let response;
instance.get('/foo').then(function (res) {
response = res;
});
@ -120,10 +120,10 @@ describe('instance', function () {
});
it('should have getUri on the instance', function() {
var instance = axios.create({
const instance = axios.create({
baseURL: 'https://api.example.com'
});
var options = {
const options = {
url: 'foo/bar',
params: {
name: 'axios'
@ -133,8 +133,8 @@ describe('instance', function () {
});
it('should correctly build url without baseURL', function () {
var instance = axios.create();
var options = {
const instance = axios.create();
const options = {
url: 'foo/bar?foo=bar',
params: {
name: 'axios'
@ -144,8 +144,8 @@ describe('instance', function () {
});
it('should correctly discard url hash mark', function () {
var instance = axios.create();
var options = {
const instance = axios.create();
const options = {
baseURL: 'https://api.example.com',
url: 'foo/bar?foo=bar#hash',
params: {

View File

@ -10,7 +10,7 @@ describe('interceptors', function () {
});
it('should add a request interceptor (asynchronous by default)', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios.interceptors.request.use(function (config) {
config.headers.test = 'added by interceptor';
expect(asyncFlag).toBe(true);
@ -27,7 +27,7 @@ describe('interceptors', function () {
});
it('should add a request interceptor (explicitly flagged as asynchronous)', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios.interceptors.request.use(function (config) {
config.headers.test = 'added by interceptor';
expect(asyncFlag).toBe(true);
@ -44,7 +44,7 @@ describe('interceptors', function () {
});
it('should add a request interceptor that is executed synchronously when flag is provided', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios.interceptors.request.use(function (config) {
config.headers.test = 'added by synchronous interceptor';
expect(asyncFlag).toBe(false);
@ -61,7 +61,7 @@ describe('interceptors', function () {
});
it('should execute asynchronously when not all interceptors are explicitly flagged as synchronous', function (done) {
var asyncFlag = false;
let asyncFlag = false;
axios.interceptors.request.use(function (config) {
config.headers.foo = 'uh oh, async';
expect(asyncFlag).toBe(true);
@ -126,7 +126,7 @@ describe('interceptors', function () {
});
it('does not run async interceptor if runWhen function is provided and resolves to false (and run synchronously)', function (done) {
var asyncFlag = false;
let asyncFlag = false;
function onPostCall(config) {
return config.method === 'post';
@ -153,13 +153,13 @@ describe('interceptors', function () {
});
it('should add a request interceptor with an onRejected block that is called if interceptor code fails', function (done) {
var rejectedSpy = jasmine.createSpy('rejectedSpy');
var error = new Error('deadly error');
const rejectedSpy = jasmine.createSpy('rejectedSpy');
const error = new Error('deadly error');
axios.interceptors.request.use(function () {
throw error;
}, rejectedSpy, { synchronous: true });
axios('/foo');
axios('/foo').catch(done);
getAjaxRequest().then(function () {
expect(rejectedSpy).toHaveBeenCalledWith(error);
@ -228,7 +228,7 @@ describe('interceptors', function () {
});
it('should add a response interceptor', function (done) {
var response;
let response;
axios.interceptors.response.use(function (data) {
data.data = data.data + ' - modified by interceptor';
@ -253,7 +253,7 @@ describe('interceptors', function () {
});
it('should add a response interceptor when request interceptor is defined', function (done) {
var response;
let response;
axios.interceptors.request.use(function (data) {
return data;
@ -282,7 +282,7 @@ describe('interceptors', function () {
});
it('should add a response interceptor that returns a new data object', function (done) {
var response;
let response;
axios.interceptors.response.use(function () {
return {
@ -308,7 +308,7 @@ describe('interceptors', function () {
});
it('should add a response interceptor that returns a promise', function (done) {
var response;
let response;
axios.interceptors.response.use(function (data) {
return new Promise(function (resolve) {
@ -342,7 +342,7 @@ describe('interceptors', function () {
describe('and when the response was fulfilled', function () {
function fireRequestAndExpect(expectation) {
var response;
let response;
axios('/foo').then(function(data) {
response = data;
});
@ -359,8 +359,8 @@ describe('interceptors', function () {
}
it('then each interceptor is executed', function (done) {
var interceptor1 = jasmine.createSpy('interceptor1');
var interceptor2 = jasmine.createSpy('interceptor2');
const interceptor1 = jasmine.createSpy('interceptor1');
const interceptor2 = jasmine.createSpy('interceptor2');
axios.interceptors.response.use(interceptor1);
axios.interceptors.response.use(interceptor2);
@ -372,8 +372,8 @@ describe('interceptors', function () {
});
it('then they are executed in the order they were added', function (done) {
var interceptor1 = jasmine.createSpy('interceptor1');
var interceptor2 = jasmine.createSpy('interceptor2');
const interceptor1 = jasmine.createSpy('interceptor1');
const interceptor2 = jasmine.createSpy('interceptor2');
axios.interceptors.response.use(interceptor1);
axios.interceptors.response.use(interceptor2);
@ -433,7 +433,7 @@ describe('interceptors', function () {
axios.interceptors.response.use(function() {
throw Error('throwing interceptor');
});
var interceptor2 = jasmine.createSpy('interceptor2');
const interceptor2 = jasmine.createSpy('interceptor2');
axios.interceptors.response.use(interceptor2);
fireRequestCatchAndExpect(function () {
@ -446,8 +446,8 @@ describe('interceptors', function () {
axios.interceptors.response.use(function() {
throw Error('throwing interceptor');
});
var unusedFulfillInterceptor = function() {};
var rejectIntercept = jasmine.createSpy('rejectIntercept');
const unusedFulfillInterceptor = function() {};
const rejectIntercept = jasmine.createSpy('rejectIntercept');
axios.interceptors.response.use(unusedFulfillInterceptor, rejectIntercept);
fireRequestCatchAndExpect(function () {
@ -455,17 +455,17 @@ describe('interceptors', function () {
done();
});
});
it('once caught, another following fulfill-interceptor is called again (just like in a promise chain)', function (done) {
axios.interceptors.response.use(function() {
throw Error('throwing interceptor');
});
var unusedFulfillInterceptor = function() {};
var catchingThrowingInterceptor = function() {};
const unusedFulfillInterceptor = function() {};
const catchingThrowingInterceptor = function() {};
axios.interceptors.response.use(unusedFulfillInterceptor, catchingThrowingInterceptor);
var interceptor3 = jasmine.createSpy('interceptor3');
const interceptor3 = jasmine.createSpy('interceptor3');
axios.interceptors.response.use(interceptor3);
fireRequestCatchAndExpect(function () {
@ -478,7 +478,7 @@ describe('interceptors', function () {
});
it('should allow removing interceptors', function (done) {
var response, intercept;
let response, intercept;
axios.interceptors.response.use(function (data) {
data.data = data.data + '1';
@ -513,13 +513,13 @@ describe('interceptors', function () {
});
it('should remove async interceptor before making request and execute synchronously', function (done) {
var asyncFlag = false;
var asyncIntercept = axios.interceptors.request.use(function (config) {
let asyncFlag = false;
const asyncIntercept = axios.interceptors.request.use(function (config) {
config.headers.async = 'async it!';
return config;
}, null, { synchronous: false });
var syncIntercept = axios.interceptors.request.use(function (config) {
const syncIntercept = axios.interceptors.request.use(function (config) {
config.headers.sync = 'hello world';
expect(asyncFlag).toBe(false);
return config;
@ -555,7 +555,7 @@ describe('interceptors', function () {
});
it('should modify base URL in request interceptor', function (done) {
var instance = axios.create({
const instance = axios.create({
baseURL: 'http://test.com/'
});
@ -573,7 +573,7 @@ describe('interceptors', function () {
});
it('should clear all request interceptors', function () {
var instance = axios.create({
const instance = axios.create({
baseURL: 'http://test.com/'
});
@ -587,7 +587,7 @@ describe('interceptors', function () {
});
it('should clear all response interceptors', function () {
var instance = axios.create({
const instance = axios.create({
baseURL: 'http://test.com/'
});

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