diff --git a/index.d.ts b/index.d.ts index bbf8390..3a7d5f1 100644 --- a/index.d.ts +++ b/index.d.ts @@ -2,213 +2,26 @@ type AxiosHeaders = Record; type MethodsHeaders = { - [Key in Method as Lowercase]: AxiosHeaders; + [Key in axios.Method as Lowercase]: AxiosHeaders; }; interface CommonHeaders { common: AxiosHeaders; } -export type AxiosRequestHeaders = Partial; - -export type AxiosResponseHeaders = Record & { - "set-cookie"?: string[] -}; - -export interface AxiosRequestTransformer { - (data: any, headers: AxiosRequestHeaders): any; -} - -export interface AxiosResponseTransformer { - (data: any, headers?: AxiosResponseHeaders, status?: number): any; -} - -export interface AxiosAdapter { - (config: AxiosRequestConfig): AxiosPromise; -} - -export interface AxiosBasicCredentials { - username: string; - password: string; -} - -export interface AxiosProxyConfig { - host: string; - port: number; - auth?: { - username: string; - password: string; - }; - protocol?: string; -} - -export type Method = - | 'get' | 'GET' - | 'delete' | 'DELETE' - | 'head' | 'HEAD' - | 'options' | 'OPTIONS' - | 'post' | 'POST' - | 'put' | 'PUT' - | 'patch' | 'PATCH' - | 'purge' | 'PURGE' - | 'link' | 'LINK' - | 'unlink' | 'UNLINK'; - -export type ResponseType = - | 'arraybuffer' - | 'blob' - | 'document' - | 'json' - | 'text' - | 'stream'; - - export type responseEncoding = - | 'ascii' | 'ASCII' - | 'ansi' | 'ANSI' - | 'binary' | 'BINARY' - | 'base64' | 'BASE64' - | 'base64url' | 'BASE64URL' - | 'hex' | 'HEX' - | 'latin1' | 'LATIN1' - | 'ucs-2' | 'UCS-2' - | 'ucs2' | 'UCS2' - | 'utf-8' | 'UTF-8' - | 'utf8' | 'UTF8' - | 'utf16le' | 'UTF16LE'; - -export interface TransitionalOptions { - silentJSONParsing?: boolean; - forcedJSONParsing?: boolean; - clarifyTimeoutError?: boolean; -} - -export interface GenericAbortSignal { - aborted: boolean; - onabort: ((...args: any) => any) | null; - addEventListener: (...args: any) => any; - removeEventListener: (...args: any) => any; -} - -export interface FormDataVisitorHelpers { - defaultVisitor: SerializerVisitor; - convertValue: (value: any) => any; - isVisitable: (value: any) => boolean; -} - -export interface SerializerVisitor { - ( - this: GenericFormData, - value: any, - key: string | number, - path: null | Array, - helpers: FormDataVisitorHelpers - ): boolean; -} - -export interface SerializerOptions { - visitor?: SerializerVisitor; - dots?: boolean; - metaTokens?: boolean; - indexes?: boolean; -} - -// tslint:disable-next-line -export interface FormSerializerOptions extends SerializerOptions { -} - -export interface ParamEncoder { - (value: any, defaultEncoder: (value: any) => any): any; -} - -export interface ParamsSerializerOptions extends SerializerOptions { - encode?: ParamEncoder; -} - -export interface AxiosRequestConfig { - url?: string; - method?: Method | string; - baseURL?: string; - transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; - transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; - headers?: AxiosRequestHeaders; - params?: any; - paramsSerializer?: ParamsSerializerOptions; - data?: D; - timeout?: number; - timeoutErrorMessage?: string; - withCredentials?: boolean; - adapter?: AxiosAdapter; - auth?: AxiosBasicCredentials; - responseType?: ResponseType; - responseEncoding?: responseEncoding | string; - xsrfCookieName?: string; - xsrfHeaderName?: string; - onUploadProgress?: (progressEvent: ProgressEvent) => void; - onDownloadProgress?: (progressEvent: ProgressEvent) => void; - maxContentLength?: number; - validateStatus?: ((status: number) => boolean) | null; - maxBodyLength?: number; - maxRedirects?: number; - beforeRedirect?: (options: Record, responseDetails: {headers: Record}) => void; - socketPath?: string | null; - httpAgent?: any; - httpsAgent?: any; - proxy?: AxiosProxyConfig | false; - cancelToken?: CancelToken; - decompress?: boolean; - transitional?: TransitionalOptions; - signal?: GenericAbortSignal; - insecureHTTPParser?: boolean; - env?: { - FormData?: new (...args: any[]) => object; - }; - formSerializer?: FormSerializerOptions; -} - -export interface HeadersDefaults { - common: AxiosRequestHeaders; - delete: AxiosRequestHeaders; - get: AxiosRequestHeaders; - head: AxiosRequestHeaders; - post: AxiosRequestHeaders; - put: AxiosRequestHeaders; - patch: AxiosRequestHeaders; - options?: AxiosRequestHeaders; - purge?: AxiosRequestHeaders; - link?: AxiosRequestHeaders; - unlink?: AxiosRequestHeaders; -} - -export interface AxiosDefaults extends Omit, 'headers'> { - headers: HeadersDefaults; -} - -export interface CreateAxiosDefaults extends Omit, 'headers'> { - headers?: AxiosRequestHeaders | Partial; -} - -export interface AxiosResponse { - data: T; - status: number; - statusText: string; - headers: AxiosResponseHeaders; - config: AxiosRequestConfig; - request?: any; -} - -export class AxiosError extends Error { +declare class AxiosError_ extends Error { constructor( message?: string, code?: string, - config?: AxiosRequestConfig, + config?: axios.AxiosRequestConfig, request?: any, - response?: AxiosResponse + response?: axios.AxiosResponse ); - config?: AxiosRequestConfig; + config?: axios.AxiosRequestConfig; code?: string; request?: any; - response?: AxiosResponse; + response?: axios.AxiosResponse; isAxiosError: boolean; status?: number; toJSON: () => object; @@ -227,106 +40,300 @@ export class AxiosError extends Error { static readonly ETIMEDOUT = "ETIMEDOUT"; } -export class CanceledError extends AxiosError { +declare class CanceledError_ extends AxiosError_ { } -export type AxiosPromise = Promise>; - -export interface CancelStatic { - new (message?: string): Cancel; -} - -export interface Cancel { - message: string | undefined; -} - -export interface Canceler { - (message?: string, config?: AxiosRequestConfig, request?: any): void; -} - -export interface CancelTokenStatic { - new (executor: (cancel: Canceler) => void): CancelToken; - source(): CancelTokenSource; -} - -export interface CancelToken { - promise: Promise; - reason?: Cancel; - throwIfRequested(): void; -} - -export interface CancelTokenSource { - token: CancelToken; - cancel: Canceler; -} - -export interface AxiosInterceptorOptions { - synchronous?: boolean; - runWhen?: (config: AxiosRequestConfig) => boolean; -} - -export interface AxiosInterceptorManager { - use(onFulfilled?: (value: V) => T | Promise, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number; - eject(id: number): void; -} - -export class Axios { - constructor(config?: AxiosRequestConfig); - defaults: AxiosDefaults; +declare class Axios_ { + constructor(config?: axios.AxiosRequestConfig); + defaults: axios.AxiosDefaults; interceptors: { - request: AxiosInterceptorManager; - response: AxiosInterceptorManager; + request: axios.AxiosInterceptorManager; + response: axios.AxiosInterceptorManager; }; - getUri(config?: AxiosRequestConfig): string; - request, D = any>(config: AxiosRequestConfig): Promise; - get, D = any>(url: string, config?: AxiosRequestConfig): Promise; - delete, D = any>(url: string, config?: AxiosRequestConfig): Promise; - head, D = any>(url: string, config?: AxiosRequestConfig): Promise; - options, D = any>(url: string, config?: AxiosRequestConfig): Promise; - post, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; - put, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; - patch, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; - postForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; - putForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; - patchForm, D = any>(url: string, data?: D, config?: AxiosRequestConfig): Promise; + getUri(config?: axios.AxiosRequestConfig): string; + request, D = any>(config: axios.AxiosRequestConfig): Promise; + get, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + delete, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + head, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + options, D = any>(url: string, config?: axios.AxiosRequestConfig): Promise; + post, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + put, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patch, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + postForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + putForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; + patchForm, D = any>(url: string, data?: D, config?: axios.AxiosRequestConfig): Promise; } -export interface AxiosInstance extends Axios { - , D = any>(config: AxiosRequestConfig): AxiosPromise; - , D = any>(url: string, config?: AxiosRequestConfig): AxiosPromise; +declare namespace axios { + type AxiosRequestHeaders = Partial; - defaults: Omit & { - headers: HeadersDefaults & { - [key: string]: string | number | boolean | undefined - } + type AxiosResponseHeaders = Record & { + "set-cookie"?: string[] }; + + interface AxiosRequestTransformer { + (data: any, headers: AxiosRequestHeaders): any; + } + + interface AxiosResponseTransformer { + (data: any, headers?: AxiosResponseHeaders, status?: number): any; + } + + interface AxiosAdapter { + (config: AxiosRequestConfig): AxiosPromise; + } + + interface AxiosBasicCredentials { + username: string; + password: string; + } + + interface AxiosProxyConfig { + host: string; + port: number; + auth?: { + username: string; + password: string; + }; + protocol?: string; + } + + type Method = + | 'get' | 'GET' + | 'delete' | 'DELETE' + | 'head' | 'HEAD' + | 'options' | 'OPTIONS' + | 'post' | 'POST' + | 'put' | 'PUT' + | 'patch' | 'PATCH' + | 'purge' | 'PURGE' + | 'link' | 'LINK' + | 'unlink' | 'UNLINK'; + + type ResponseType = + | 'arraybuffer' + | 'blob' + | 'document' + | 'json' + | 'text' + | 'stream'; + + 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'; + + interface TransitionalOptions { + silentJSONParsing?: boolean; + forcedJSONParsing?: boolean; + clarifyTimeoutError?: boolean; + } + + interface GenericAbortSignal { + aborted: boolean; + onabort: ((...args: any) => any) | null; + addEventListener: (...args: any) => any; + removeEventListener: (...args: any) => any; + } + + interface FormDataVisitorHelpers { + defaultVisitor: SerializerVisitor; + convertValue: (value: any) => any; + isVisitable: (value: any) => boolean; + } + + interface SerializerVisitor { + ( + this: GenericFormData, + value: any, + key: string | number, + path: null | Array, + helpers: FormDataVisitorHelpers + ): boolean; + } + + interface SerializerOptions { + visitor?: SerializerVisitor; + dots?: boolean; + metaTokens?: boolean; + indexes?: boolean; + } + + // tslint:disable-next-line + interface FormSerializerOptions extends SerializerOptions { + } + + interface ParamEncoder { + (value: any, defaultEncoder: (value: any) => any): any; + } + + interface ParamsSerializerOptions extends SerializerOptions { + encode?: ParamEncoder; + } + + interface AxiosRequestConfig { + url?: string; + method?: Method | string; + baseURL?: string; + transformRequest?: AxiosRequestTransformer | AxiosRequestTransformer[]; + transformResponse?: AxiosResponseTransformer | AxiosResponseTransformer[]; + headers?: AxiosRequestHeaders; + params?: any; + paramsSerializer?: ParamsSerializerOptions; + data?: D; + timeout?: number; + timeoutErrorMessage?: string; + withCredentials?: boolean; + adapter?: AxiosAdapter; + auth?: AxiosBasicCredentials; + responseType?: ResponseType; + responseEncoding?: responseEncoding | string; + xsrfCookieName?: string; + xsrfHeaderName?: string; + onUploadProgress?: (progressEvent: ProgressEvent) => void; + onDownloadProgress?: (progressEvent: ProgressEvent) => void; + maxContentLength?: number; + validateStatus?: ((status: number) => boolean) | null; + maxBodyLength?: number; + maxRedirects?: number; + beforeRedirect?: (options: Record, responseDetails: {headers: Record}) => void; + socketPath?: string | null; + httpAgent?: any; + httpsAgent?: any; + proxy?: AxiosProxyConfig | false; + cancelToken?: CancelToken; + decompress?: boolean; + transitional?: TransitionalOptions; + signal?: GenericAbortSignal; + insecureHTTPParser?: boolean; + env?: { + FormData?: new (...args: any[]) => object; + }; + formSerializer?: FormSerializerOptions; + } + + interface HeadersDefaults { + common: AxiosRequestHeaders; + delete: AxiosRequestHeaders; + get: AxiosRequestHeaders; + head: AxiosRequestHeaders; + post: AxiosRequestHeaders; + put: AxiosRequestHeaders; + patch: AxiosRequestHeaders; + options?: AxiosRequestHeaders; + purge?: AxiosRequestHeaders; + link?: AxiosRequestHeaders; + unlink?: AxiosRequestHeaders; + } + + interface AxiosDefaults extends Omit, 'headers'> { + headers: HeadersDefaults; + } + + interface CreateAxiosDefaults extends Omit, 'headers'> { + headers?: AxiosRequestHeaders | Partial; + } + + interface AxiosResponse { + data: T; + status: number; + statusText: string; + headers: AxiosResponseHeaders; + config: AxiosRequestConfig; + request?: any; + } + + type AxiosPromise = Promise>; + + interface CancelStatic { + new (message?: string): Cancel; + } + + interface Cancel { + message: string | undefined; + } + + interface Canceler { + (message?: string, config?: AxiosRequestConfig, request?: any): void; + } + + interface CancelTokenStatic { + new (executor: (cancel: Canceler) => void): CancelToken; + source(): CancelTokenSource; + } + + interface CancelToken { + promise: Promise; + reason?: Cancel; + throwIfRequested(): void; + } + + interface CancelTokenSource { + token: CancelToken; + cancel: Canceler; + } + + interface AxiosInterceptorOptions { + synchronous?: boolean; + runWhen?: (config: AxiosRequestConfig) => boolean; + } + + interface AxiosInterceptorManager { + use(onFulfilled?: (value: V) => T | Promise, onRejected?: (error: any) => any, options?: AxiosInterceptorOptions): number; + eject(id: number): void; + } + + interface AxiosInstance extends Axios { + , D = any>(config: AxiosRequestConfig): AxiosPromise; + , D = any>(url: string, config?: AxiosRequestConfig): AxiosPromise; + + defaults: Omit & { + headers: HeadersDefaults & { + [key: string]: string | number | boolean | undefined + } + }; + } + + interface GenericFormData { + append(name: string, value: any, options?: any): any; + } + + interface GenericHTMLFormElement { + name: string; + method: string; + submit(): void; + } + + type Axios = Axios_; + type AxiosError = AxiosError_; + type CanceledError = CanceledError_; + + interface AxiosStatic extends AxiosInstance { + create(config?: CreateAxiosDefaults): AxiosInstance; + Cancel: CancelStatic; + CancelToken: CancelTokenStatic; + Axios: typeof Axios_; + AxiosError: typeof AxiosError_; + CanceledError: typeof CanceledError_; + readonly VERSION: string; + isCancel(value: any): value is Cancel; + all(values: Array>): Promise; + spread(callback: (...args: T[]) => R): (array: T[]) => R; + isAxiosError(payload: any): payload is AxiosError; + toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; + formToJSON(form: GenericFormData|GenericHTMLFormElement): object; + } } -export interface GenericFormData { - append(name: string, value: any, options?: any): any; -} +declare const axios: axios.AxiosStatic; -export interface GenericHTMLFormElement { - name: string; - method: string; - submit(): void; -} - -export interface AxiosStatic extends AxiosInstance { - create(config?: CreateAxiosDefaults): AxiosInstance; - Cancel: CancelStatic; - CancelToken: CancelTokenStatic; - Axios: typeof Axios; - AxiosError: typeof AxiosError; - readonly VERSION: string; - isCancel(value: any): value is Cancel; - all(values: Array>): Promise; - spread(callback: (...args: T[]) => R): (array: T[]) => R; - isAxiosError(payload: any): payload is AxiosError; - toFormData(sourceObj: object, targetFormData?: GenericFormData, options?: FormSerializerOptions): GenericFormData; - formToJSON(form: GenericFormData|GenericHTMLFormElement): object; -} - -declare const axios: AxiosStatic; - -export default axios; +export = axios; diff --git a/test/typescript/axios.ts b/test/typescript/axios.ts index c0c6159..1b30f4a 100644 --- a/test/typescript/axios.ts +++ b/test/typescript/axios.ts @@ -1,16 +1,6 @@ -import axios, { - AxiosRequestConfig, - AxiosResponse, - AxiosError, - AxiosInstance, - AxiosAdapter, - Cancel, - CancelToken, - CancelTokenSource, - Canceler -} from 'axios'; +import axios = require('axios'); -const config: AxiosRequestConfig = { +const config: axios.AxiosRequestConfig = { url: '/user', method: 'get', baseURL: 'https://api.example.com/', @@ -44,18 +34,18 @@ const config: AxiosRequestConfig = { host: '127.0.0.1', port: 9000 }, - cancelToken: new axios.CancelToken((cancel: Canceler) => {}) + cancelToken: new axios.CancelToken((cancel: axios.Canceler) => {}) }; -const nullValidateStatusConfig: AxiosRequestConfig = { +const nullValidateStatusConfig: axios.AxiosRequestConfig = { validateStatus: null }; -const undefinedValidateStatusConfig: AxiosRequestConfig = { +const undefinedValidateStatusConfig: axios.AxiosRequestConfig = { validateStatus: undefined }; -const handleResponse = (response: AxiosResponse) => { +const handleResponse = (response: axios.AxiosResponse) => { console.log(response.data); console.log(response.status); console.log(response.statusText); @@ -63,7 +53,7 @@ const handleResponse = (response: AxiosResponse) => { console.log(response.config); }; -const handleError = (error: AxiosError) => { +const handleError = (error: axios.AxiosError) => { if (error.response) { console.log(error.response.data); console.log(error.response.status); @@ -125,7 +115,7 @@ interface User { // with default AxiosResponse result -const handleUserResponse = (response: AxiosResponse) => { +const handleUserResponse = (response: axios.AxiosResponse) => { console.log(response.data.id); console.log(response.data.name); console.log(response.status); @@ -221,8 +211,8 @@ axios.request({ // Instances -const instance1: AxiosInstance = axios.create(); -const instance2: AxiosInstance = axios.create(config); +const instance1: axios.AxiosInstance = axios.create(); +const instance2: axios.AxiosInstance = axios.create(config); instance1(config) .then(handleResponse) @@ -274,39 +264,39 @@ axios.create({ headers: { common: { foo: 'bar' } } }); // Interceptors const requestInterceptorId: number = axios.interceptors.request.use( - (config: AxiosRequestConfig) => config, + (config: axios.AxiosRequestConfig) => config, (error: any) => Promise.reject(error) ); axios.interceptors.request.eject(requestInterceptorId); axios.interceptors.request.use( - (config: AxiosRequestConfig) => Promise.resolve(config), + (config: axios.AxiosRequestConfig) => Promise.resolve(config), (error: any) => Promise.reject(error) ); -axios.interceptors.request.use((config: AxiosRequestConfig) => config); -axios.interceptors.request.use((config: AxiosRequestConfig) => Promise.resolve(config)); +axios.interceptors.request.use((config: axios.AxiosRequestConfig) => config); +axios.interceptors.request.use((config: axios.AxiosRequestConfig) => Promise.resolve(config)); const responseInterceptorId: number = axios.interceptors.response.use( - (response: AxiosResponse) => response, + (response: axios.AxiosResponse) => response, (error: any) => Promise.reject(error) ); axios.interceptors.response.eject(responseInterceptorId); axios.interceptors.response.use( - (response: AxiosResponse) => Promise.resolve(response), + (response: axios.AxiosResponse) => Promise.resolve(response), (error: any) => Promise.reject(error) ); -axios.interceptors.response.use((response: AxiosResponse) => response); -axios.interceptors.response.use((response: AxiosResponse) => Promise.resolve(response)); +axios.interceptors.response.use((response: axios.AxiosResponse) => response); +axios.interceptors.response.use((response: axios.AxiosResponse) => Promise.resolve(response)); // Adapters -const adapter: AxiosAdapter = (config: AxiosRequestConfig) => { - const response: AxiosResponse = { +const adapter: axios.AxiosAdapter = (config: axios.AxiosRequestConfig) => { + const response: axios.AxiosResponse = { data: { foo: 'bar' }, status: 200, statusText: 'OK', @@ -335,19 +325,19 @@ const fn2: (arr: number[]) => string = axios.spread(fn1); // Promises axios.get('/user') - .then((response: AxiosResponse) => 'foo') + .then((response: axios.AxiosResponse) => 'foo') .then((value: string) => {}); axios.get('/user') - .then((response: AxiosResponse) => Promise.resolve('foo')) + .then((response: axios.AxiosResponse) => Promise.resolve('foo')) .then((value: string) => {}); axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 'bar') + .then((response: axios.AxiosResponse) => 'foo', (error: any) => 'bar') .then((value: string) => {}); axios.get('/user') - .then((response: AxiosResponse) => 'foo', (error: any) => 123) + .then((response: axios.AxiosResponse) => 'foo', (error: any) => 123) .then((value: string | number) => {}); axios.get('/user') @@ -360,13 +350,13 @@ axios.get('/user') // Cancellation -const source: CancelTokenSource = axios.CancelToken.source(); +const source: axios.CancelTokenSource = axios.CancelToken.source(); axios.get('/user', { cancelToken: source.token -}).catch((thrown: AxiosError | Cancel) => { +}).catch((thrown: axios.AxiosError | axios.Cancel) => { if (axios.isCancel(thrown)) { - const cancel: Cancel = thrown; + const cancel: axios.Cancel = thrown; console.log(cancel.message); } }); @@ -378,7 +368,7 @@ source.cancel('Operation has been canceled.'); axios.get('/user') .catch((error) => { if (axios.isAxiosError(error)) { - const axiosError: AxiosError = error; + const axiosError: axios.AxiosError = error; } }); diff --git a/tsconfig.json b/tsconfig.json index 6665188..815d633 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,6 @@ { "compilerOptions": { - "module": "es2015", + "module": "commonjs", "lib": ["dom", "es2015"], "types": [], "moduleResolution": "node",