index.d.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import * as https from 'https';
  2. import * as http from 'http';
  3. import { IncomingHttpHeaders, OutgoingHttpHeaders } from 'http';
  4. import * as url from 'url';
  5. import { Readable, Writable } from 'stream';
  6. import { EventEmitter } from 'events';
  7. import { LookupFunction } from 'net';
  8. export { IncomingHttpHeaders, OutgoingHttpHeaders };
  9. export type HttpMethod = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "OPTIONS" | "PATCH" | "TRACE" | "CONNECT";
  10. export as namespace urllib;
  11. export interface RequestOptions {
  12. /** Request method, defaults to GET. Could be GET, POST, DELETE or PUT. Alias 'type'. */
  13. method?: HttpMethod;
  14. /** Alias method */
  15. type?: HttpMethod;
  16. /** Data to be sent. Will be stringify automatically. */
  17. data?: any;
  18. /** Force convert data to query string. */
  19. dataAsQueryString?: boolean;
  20. /** Manually set the content of payload. If set, data will be ignored. */
  21. content?: string | Buffer;
  22. /** Stream to be pipe to the remote.If set, data and content will be ignored. */
  23. stream?: Readable;
  24. /**
  25. * A writable stream to be piped by the response stream.
  26. * Responding data will be write to this stream and callback
  27. * will be called with data set null after finished writing.
  28. */
  29. writeStream?: Writable;
  30. /** consume the writeStream, invoke the callback after writeStream close. */
  31. consumeWriteStream?: boolean;
  32. /**
  33. * The files will send with multipart/form-data format, base on formstream.
  34. * If method not set, will use POST method by default.
  35. */
  36. files?: Array<Readable | Buffer | string> | object | Readable | Buffer | string;
  37. /** Type of request data.Could be json.If it's json, will auto set Content-Type: application/json header. */
  38. contentType?: string;
  39. /**
  40. * urllib default use querystring to stringify form data which don't support nested object,
  41. * will use qs instead of querystring to support nested object by set this option to true.
  42. */
  43. nestedQuerystring?: boolean;
  44. /**
  45. * Type of response data. Could be text or json.
  46. * If it's text, the callbacked data would be a String.
  47. * If it's json, the data of callback would be a parsed JSON Object
  48. * and will auto set Accept: application/json header. Default callbacked data would be a Buffer.
  49. */
  50. dataType?: string;
  51. /** Fix the control characters (U+0000 through U+001F) before JSON parse response. Default is false. */
  52. fixJSONCtlChars?: boolean;
  53. /** Request headers. */
  54. headers?: IncomingHttpHeaders;
  55. /** by default will convert header keys to lowercase */
  56. keepHeaderCase?: boolean;
  57. /**
  58. * Request timeout in milliseconds for connecting phase and response receiving phase.
  59. * Defaults to exports.
  60. * TIMEOUT, both are 5s.You can use timeout: 5000 to tell urllib use same timeout on two phase or set them seperately such as
  61. * timeout: [3000, 5000], which will set connecting timeout to 3s and response 5s.
  62. */
  63. timeout?: number | number[];
  64. /** username:password used in HTTP Basic Authorization. */
  65. auth?: string;
  66. /** username:password used in HTTP Digest Authorization. */
  67. digestAuth?: string;
  68. /** HTTP Agent object.Set false if you does not use agent. */
  69. agent?: http.Agent;
  70. /** HTTPS Agent object. Set false if you does not use agent. */
  71. httpsAgent?: https.Agent;
  72. /**
  73. * An array of strings or Buffers of trusted certificates.
  74. * If this is omitted several well known "root" CAs will be used, like VeriSign.
  75. * These are used to authorize connections.
  76. * Notes: This is necessary only if the server uses the self - signed certificate
  77. */
  78. ca?: string | Buffer | string[] | Buffer[];
  79. /**
  80. * If true, the server certificate is verified against the list of supplied CAs.
  81. * An 'error' event is emitted if verification fails.Default: true.
  82. */
  83. rejectUnauthorized?: boolean;
  84. /** A string or Buffer containing the private key, certificate and CA certs of the server in PFX or PKCS12 format. */
  85. pfx?: string | Buffer;
  86. /**
  87. * A string or Buffer containing the private key of the client in PEM format.
  88. * Notes: This is necessary only if using the client certificate authentication
  89. */
  90. key?: string | Buffer;
  91. /**
  92. * A string or Buffer containing the certificate key of the client in PEM format.
  93. * Notes: This is necessary only if using the client certificate authentication
  94. */
  95. cert?: string | Buffer;
  96. /** A string of passphrase for the private key or pfx. */
  97. passphrase?: string;
  98. /** A string describing the ciphers to use or exclude. */
  99. ciphers?: string;
  100. /** The SSL method to use, e.g.SSLv3_method to force SSL version 3. */
  101. secureProtocol?: string;
  102. /** follow HTTP 3xx responses as redirects. defaults to false. */
  103. followRedirect?: boolean;
  104. /** The maximum number of redirects to follow, defaults to 10. */
  105. maxRedirects?: number;
  106. /** Format the redirect url by your self. Default is url.resolve(from, to). */
  107. formatRedirectUrl?: (a: any, b: any) => void;
  108. /** Before request hook, you can change every thing here. */
  109. beforeRequest?: (...args: any[]) => void;
  110. /** let you get the res object when request connected, default false. alias customResponse */
  111. streaming?: boolean;
  112. /** Accept gzip response content and auto decode it, default is false. */
  113. gzip?: boolean;
  114. /** Enable timing or not, default is false. */
  115. timing?: boolean;
  116. /** Enable proxy request, default is false. */
  117. enableProxy?: boolean;
  118. /** proxy agent uri or options, default is null. */
  119. proxy?: string | { [key: string]: any };
  120. /**
  121. * Custom DNS lookup function, default is dns.lookup.
  122. * Require node >= 4.0.0(for http protocol) and node >=8(for https protocol)
  123. */
  124. lookup?: LookupFunction;
  125. /**
  126. * check request address to protect from SSRF and similar attacks.
  127. * It receive two arguments(ip and family) and should return true or false to identified the address is legal or not.
  128. * It rely on lookup and have the same version requirement.
  129. */
  130. checkAddress?: (ip: string, family: number | string) => boolean;
  131. /**
  132. * UNIX domain socket path. (Windows is not supported)
  133. */
  134. socketPath?: string;
  135. }
  136. export interface HttpClientResponse<T> {
  137. data: T;
  138. status: number;
  139. headers: OutgoingHttpHeaders;
  140. res: http.IncomingMessage & {
  141. /**
  142. * https://eggjs.org/en/core/httpclient.html#timing-boolean
  143. */
  144. timing?: {
  145. queuing: number;
  146. dnslookup: number;
  147. connected: number;
  148. requestSent: number;
  149. waiting: number;
  150. contentDownload: number;
  151. }
  152. };
  153. }
  154. /**
  155. * @param data Outgoing message
  156. * @param res http response
  157. */
  158. export type Callback<T> = (err: Error, data: T, res: http.IncomingMessage) => void;
  159. /**
  160. * Handle all http request, both http and https support well.
  161. *
  162. * @example
  163. * // GET http://httptest.cnodejs.net
  164. * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {});
  165. * // POST http://httptest.cnodejs.net
  166. * var args = { type: 'post', data: { foo: 'bar' } };
  167. * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {});
  168. *
  169. * @param url The URL to request, either a String or a Object that return by url.parse.
  170. */
  171. export function request<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>;
  172. /**
  173. * @param url The URL to request, either a String or a Object that return by url.parse.
  174. */
  175. export function request<T = any>(url: string | url.URL, callback: Callback<T>): void;
  176. /**
  177. * @param url The URL to request, either a String or a Object that return by url.parse.
  178. */
  179. export function request<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  180. /**
  181. * Handle request with a callback.
  182. * @param url The URL to request, either a String or a Object that return by url.parse.
  183. */
  184. export function requestWithCallback<T = any>(url: string | url.URL, callback: Callback<T>): void;
  185. /**
  186. * @param url The URL to request, either a String or a Object that return by url.parse.
  187. */
  188. export function requestWithCallback<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  189. /**
  190. * yield urllib.requestThunk(url, args)
  191. * @param url The URL to request, either a String or a Object that return by url.parse.
  192. */
  193. export function requestThunk<T = any>(url: string | url.URL, options?: RequestOptions): (callback: Callback<T>) => void;
  194. /**
  195. * alias to request.
  196. * Handle all http request, both http and https support well.
  197. *
  198. * @example
  199. * // GET http://httptest.cnodejs.net
  200. * urllib.request('http://httptest.cnodejs.net/test/get', function(err, data, res) {});
  201. * // POST http://httptest.cnodejs.net
  202. * var args = { type: 'post', data: { foo: 'bar' } };
  203. * urllib.request('http://httptest.cnodejs.net/test/post', args, function(err, data, res) {});
  204. *
  205. * @param url The URL to request, either a String or a Object that return by url.parse.
  206. * @param options Optional, @see RequestOptions.
  207. */
  208. export function curl<T = any>(url: string | url.URL, options?: RequestOptions): Promise<HttpClientResponse<T>>;
  209. /**
  210. * @param url The URL to request, either a String or a Object that return by url.parse.
  211. */
  212. export function curl<T = any>(url: string | url.URL, callback: Callback<T>): void;
  213. /**
  214. * @param url The URL to request, either a String or a Object that return by url.parse.
  215. */
  216. export function curl<T = any>(url: string | url.URL, options: RequestOptions, callback: Callback<T>): void;
  217. /**
  218. * The default request timeout(in milliseconds).
  219. */
  220. export const TIMEOUT: number;
  221. /**
  222. * The default request & response timeout(in milliseconds).
  223. */
  224. export const TIMEOUTS: [number, number];
  225. /**
  226. * Request user agent.
  227. */
  228. export const USER_AGENT: string;
  229. /**
  230. * Request http agent.
  231. */
  232. export const agent: http.Agent;
  233. /**
  234. * Request https agent.
  235. */
  236. export const httpsAgent: https.Agent;
  237. export class HttpClient<O extends RequestOptions = RequestOptions> extends EventEmitter {
  238. request<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>;
  239. request<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>;
  240. request<T = any>(url: string | url.URL, callback: Callback<T>): void;
  241. request<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void;
  242. curl<T = any>(url: string | url.URL, options: O): Promise<HttpClientResponse<T>>;
  243. curl<T = any>(url: string | url.URL): Promise<HttpClientResponse<T>>;
  244. curl<T = any>(url: string | url.URL, callback: Callback<T>): void;
  245. curl<T = any>(url: string | url.URL, options: O, callback: Callback<T>): void;
  246. requestThunk(url: string | url.URL, options?: O): (callback: (...args: any[]) => void) => void;
  247. }
  248. export interface RequestOptions2 extends RequestOptions {
  249. retry?: number;
  250. retryDelay?: number;
  251. isRetry?: (res: HttpClientResponse<any>) => boolean;
  252. }
  253. /**
  254. * request method only return a promise,
  255. * compatible with async/await and generator in co.
  256. */
  257. export class HttpClient2 extends HttpClient<RequestOptions2> {}
  258. /**
  259. * Create a HttpClient instance.
  260. */
  261. export function create(options?: RequestOptions): HttpClient;