UNPKG

42.8 kBTypeScriptView Raw
1/// <reference types="node" />
2import { Duplex, Readable } from 'stream';
3import { URL, URLSearchParams } from 'url';
4import { Socket } from 'net';
5import { SecureContextOptions, DetailedPeerCertificate } from 'tls';
6import http = require('http');
7import { ClientRequest, RequestOptions, ServerResponse, request as httpRequest } from 'http';
8import https = require('https');
9import { Timings, IncomingMessageWithTimings } from '@szmarczak/http-timer';
10import CacheableLookup from 'cacheable-lookup';
11import CacheableRequest = require('cacheable-request');
12import ResponseLike = require('responselike');
13import { Delays, TimeoutError as TimedOutTimeoutError } from './utils/timed-out';
14import { URLOptions } from './utils/options-to-url';
15import { DnsLookupIpVersion } from './utils/dns-ip-version';
16import { PromiseOnly } from '../as-promise/types';
17declare type HttpRequestFunction = typeof httpRequest;
18declare type Error = NodeJS.ErrnoException;
19declare const kRequest: unique symbol;
20declare const kResponse: unique symbol;
21declare const kResponseSize: unique symbol;
22declare const kDownloadedSize: unique symbol;
23declare const kBodySize: unique symbol;
24declare const kUploadedSize: unique symbol;
25declare const kServerResponsesPiped: unique symbol;
26declare const kUnproxyEvents: unique symbol;
27declare const kIsFromCache: unique symbol;
28declare const kCancelTimeouts: unique symbol;
29declare const kStartedReading: unique symbol;
30declare const kStopReading: unique symbol;
31declare const kTriggerRead: unique symbol;
32declare const kBody: unique symbol;
33declare const kJobs: unique symbol;
34declare const kOriginalResponse: unique symbol;
35declare const kRetryTimeout: unique symbol;
36export declare const kIsNormalizedAlready: unique symbol;
37export interface Agents {
38 http?: http.Agent;
39 https?: https.Agent;
40 http2?: unknown;
41}
42export declare const withoutBody: ReadonlySet<string>;
43export interface ToughCookieJar {
44 getCookieString: ((currentUrl: string, options: Record<string, unknown>, cb: (err: Error | null, cookies: string) => void) => void) & ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void);
45 setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record<string, unknown>, cb: (err: Error | null, cookie: unknown) => void) => void) & ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void);
46}
47export interface PromiseCookieJar {
48 getCookieString: (url: string) => Promise<string>;
49 setCookie: (rawCookie: string, url: string) => Promise<unknown>;
50}
51/**
52All available HTTP request methods provided by Got.
53*/
54export declare type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD' | 'DELETE' | 'OPTIONS' | 'TRACE' | 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete' | 'options' | 'trace';
55declare type Promisable<T> = T | Promise<T>;
56export declare type InitHook = (options: Options) => void;
57export declare type BeforeRequestHook = (options: NormalizedOptions) => Promisable<void | Response | ResponseLike>;
58export declare type BeforeRedirectHook = (options: NormalizedOptions, response: Response) => Promisable<void>;
59export declare type BeforeErrorHook = (error: RequestError) => Promisable<RequestError>;
60export declare type BeforeRetryHook = (options: NormalizedOptions, error?: RequestError, retryCount?: number) => void | Promise<void>;
61interface PlainHooks {
62 /**
63 Called with plain request options, right before their normalization.
64 This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
65
66 __Note #1__: This hook must be synchronous!
67
68 __Note #2__: Errors in this hook will be converted into an instances of `RequestError`.
69
70 __Note #3__: The options object may not have a `url` property.
71 To modify it, use a `beforeRequest` hook instead.
72
73 @default []
74 */
75 init?: InitHook[];
76 /**
77 Called with normalized request options.
78 Got will make no further changes to the request before it is sent.
79 This is especially useful in conjunction with `got.extend()` when you want to create an API client that, for example, uses HMAC-signing.
80
81 @default []
82 */
83 beforeRequest?: BeforeRequestHook[];
84 /**
85 Called with normalized request options and the redirect response.
86 Got will make no further changes to the request.
87 This is especially useful when you want to avoid dead sites.
88
89 @default []
90
91 @example
92 ```
93 const got = require('got');
94
95 got('https://example.com', {
96 hooks: {
97 beforeRedirect: [
98 (options, response) => {
99 if (options.hostname === 'deadSite') {
100 options.hostname = 'fallbackSite';
101 }
102 }
103 ]
104 }
105 });
106 ```
107 */
108 beforeRedirect?: BeforeRedirectHook[];
109 /**
110 Called with an `Error` instance.
111 The error is passed to the hook right before it's thrown.
112 This is especially useful when you want to have more detailed errors.
113
114 __Note__: Errors thrown while normalizing input options are thrown directly and not part of this hook.
115
116 @default []
117
118 @example
119 ```
120 const got = require('got');
121
122 got('https://api.github.com/some-endpoint', {
123 hooks: {
124 beforeError: [
125 error => {
126 const {response} = error;
127 if (response && response.body) {
128 error.name = 'GitHubError';
129 error.message = `${response.body.message} (${response.statusCode})`;
130 }
131
132 return error;
133 }
134 ]
135 }
136 });
137 ```
138 */
139 beforeError?: BeforeErrorHook[];
140 /**
141 Called with normalized request options, the error and the retry count.
142 Got will make no further changes to the request.
143 This is especially useful when some extra work is required before the next try.
144
145 __Note__: When using streams, this hook is ignored.
146 __Note__: When retrying in a `afterResponse` hook, all remaining `beforeRetry` hooks will be called without the `error` and `retryCount` arguments.
147
148 @default []
149
150 @example
151 ```
152 const got = require('got');
153
154 got.post('https://example.com', {
155 hooks: {
156 beforeRetry: [
157 (options, error, retryCount) => {
158 if (error.response.statusCode === 413) { // Payload too large
159 options.body = getNewBody();
160 }
161 }
162 ]
163 }
164 });
165 ```
166 */
167 beforeRetry?: BeforeRetryHook[];
168}
169/**
170All available hook of Got.
171*/
172export interface Hooks extends PromiseOnly.Hooks, PlainHooks {
173}
174declare type PlainHookEvent = 'init' | 'beforeRequest' | 'beforeRedirect' | 'beforeError' | 'beforeRetry';
175/**
176All hook events acceptable by Got.
177*/
178export declare type HookEvent = PromiseOnly.HookEvent | PlainHookEvent;
179export declare const knownHookEvents: HookEvent[];
180declare type AcceptableResponse = IncomingMessageWithTimings | ResponseLike;
181declare type AcceptableRequestResult = AcceptableResponse | ClientRequest | Promise<AcceptableResponse | ClientRequest> | undefined;
182export declare type RequestFunction = (url: URL, options: RequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult;
183export declare type Headers = Record<string, string | string[] | undefined>;
184declare type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => Error | void;
185export declare type ParseJsonFunction = (text: string) => unknown;
186export declare type StringifyJsonFunction = (object: unknown) => string;
187export interface RetryObject {
188 attemptCount: number;
189 retryOptions: RequiredRetryOptions;
190 error: TimeoutError | RequestError;
191 computedValue: number;
192 retryAfter?: number;
193}
194export declare type RetryFunction = (retryObject: RetryObject) => number | Promise<number>;
195/**
196An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
197
198Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
199
200The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
201The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
202
203By default, it retries *only* on the specified methods, status codes, and on these network errors:
204- `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
205- `ECONNRESET`: Connection was forcibly closed by a peer.
206- `EADDRINUSE`: Could not bind to any free port.
207- `ECONNREFUSED`: Connection was refused by the server.
208- `EPIPE`: The remote side of the stream being written has been closed.
209- `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
210- `ENETUNREACH`: No internet connection.
211- `EAI_AGAIN`: DNS lookup timed out.
212
213__Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
214__Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
215*/
216export interface RequiredRetryOptions {
217 limit: number;
218 methods: Method[];
219 statusCodes: number[];
220 errorCodes: string[];
221 calculateDelay: RetryFunction;
222 maxRetryAfter?: number;
223}
224export interface CacheOptions {
225 shared?: boolean;
226 cacheHeuristic?: number;
227 immutableMinTimeToLive?: number;
228 ignoreCargoCult?: boolean;
229}
230interface PlainOptions extends URLOptions {
231 /**
232 Custom request function.
233 The main purpose of this is to [support HTTP2 using a wrapper](https://github.com/szmarczak/http2-wrapper).
234
235 @default http.request | https.request
236 */
237 request?: RequestFunction;
238 /**
239 An object representing `http`, `https` and `http2` keys for [`http.Agent`](https://nodejs.org/api/http.html#http_class_http_agent), [`https.Agent`](https://nodejs.org/api/https.html#https_class_https_agent) and [`http2wrapper.Agent`](https://github.com/szmarczak/http2-wrapper#new-http2agentoptions) instance.
240 This is necessary because a request to one protocol might redirect to another.
241 In such a scenario, Got will switch over to the right protocol agent for you.
242
243 If a key is not present, it will default to a global agent.
244
245 @example
246 ```
247 const got = require('got');
248 const HttpAgent = require('agentkeepalive');
249 const {HttpsAgent} = HttpAgent;
250
251 got('https://sindresorhus.com', {
252 agent: {
253 http: new HttpAgent(),
254 https: new HttpsAgent()
255 }
256 });
257 ```
258 */
259 agent?: Agents | false;
260 /**
261 Decompress the response automatically.
262 This will set the `accept-encoding` header to `gzip, deflate, br` on Node.js 11.7.0+ or `gzip, deflate` for older Node.js versions, unless you set it yourself.
263
264 Brotli (`br`) support requires Node.js 11.7.0 or later.
265
266 If this is disabled, a compressed response is returned as a `Buffer`.
267 This may be useful if you want to handle decompression yourself or stream the raw compressed data.
268
269 @default true
270 */
271 decompress?: boolean;
272 /**
273 Milliseconds to wait for the server to end the response before aborting the request with `got.TimeoutError` error (a.k.a. `request` property).
274 By default, there's no timeout.
275
276 This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
277
278 - `lookup` starts when a socket is assigned and ends when the hostname has been resolved.
279 Does not apply when using a Unix domain socket.
280 - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
281 - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
282 - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
283 - `response` starts when the request has been written to the socket and ends when the response headers are received.
284 - `send` starts when the socket is connected and ends with the request has been written to the socket.
285 - `request` starts when the request is initiated and ends when the response's end event fires.
286 */
287 timeout?: Delays | number;
288 /**
289 When specified, `prefixUrl` will be prepended to `url`.
290 The prefix can be any valid URL, either relative or absolute.
291 A trailing slash `/` is optional - one will be added automatically.
292
293 __Note__: `prefixUrl` will be ignored if the `url` argument is a URL instance.
294
295 __Note__: Leading slashes in `input` are disallowed when using this option to enforce consistency and avoid confusion.
296 For example, when the prefix URL is `https://example.com/foo` and the input is `/bar`, there's ambiguity whether the resulting URL would become `https://example.com/foo/bar` or `https://example.com/bar`.
297 The latter is used by browsers.
298
299 __Tip__: Useful when used with `got.extend()` to create niche-specific Got instances.
300
301 __Tip__: You can change `prefixUrl` using hooks as long as the URL still includes the `prefixUrl`.
302 If the URL doesn't include it anymore, it will throw.
303
304 @example
305 ```
306 const got = require('got');
307
308 (async () => {
309 await got('unicorn', {prefixUrl: 'https://cats.com'});
310 //=> 'https://cats.com/unicorn'
311
312 const instance = got.extend({
313 prefixUrl: 'https://google.com'
314 });
315
316 await instance('unicorn', {
317 hooks: {
318 beforeRequest: [
319 options => {
320 options.prefixUrl = 'https://cats.com';
321 }
322 ]
323 }
324 });
325 //=> 'https://cats.com/unicorn'
326 })();
327 ```
328 */
329 prefixUrl?: string | URL;
330 /**
331 __Note #1__: The `body` option cannot be used with the `json` or `form` option.
332
333 __Note #2__: If you provide this option, `got.stream()` will be read-only.
334
335 __Note #3__: If you provide a payload with the `GET` or `HEAD` method, it will throw a `TypeError` unless the method is `GET` and the `allowGetBody` option is set to `true`.
336
337 __Note #4__: This option is not enumerable and will not be merged with the instance defaults.
338
339 The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
340 */
341 body?: string | Buffer | Readable;
342 /**
343 The form body is converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
344
345 If the `Content-Type` header is not present, it will be set to `application/x-www-form-urlencoded`.
346
347 __Note #1__: If you provide this option, `got.stream()` will be read-only.
348
349 __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
350 */
351 form?: Record<string, any>;
352 /**
353 JSON body. If the `Content-Type` header is not set, it will be set to `application/json`.
354
355 __Note #1__: If you provide this option, `got.stream()` will be read-only.
356
357 __Note #2__: This option is not enumerable and will not be merged with the instance defaults.
358 */
359 json?: Record<string, any>;
360 /**
361 The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
362
363 Properties from `options` will override properties in the parsed `url`.
364
365 If no protocol is specified, it will throw a `TypeError`.
366
367 __Note__: The query string is **not** parsed as search params.
368
369 @example
370 ```
371 got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
372 got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
373
374 // The query string is overridden by `searchParams`
375 got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
376 ```
377 */
378 url?: string | URL;
379 /**
380 Cookie support. You don't have to care about parsing or how to store them.
381
382 __Note__: If you provide this option, `options.headers.cookie` will be overridden.
383 */
384 cookieJar?: PromiseCookieJar | ToughCookieJar;
385 /**
386 Ignore invalid cookies instead of throwing an error.
387 Only useful when the `cookieJar` option has been set. Not recommended.
388
389 @default false
390 */
391 ignoreInvalidCookies?: boolean;
392 /**
393 Query string that will be added to the request URL.
394 This will override the query string in `url`.
395
396 If you need to pass in an array, you can do it using a `URLSearchParams` instance.
397
398 @example
399 ```
400 const got = require('got');
401
402 const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
403
404 got('https://example.com', {searchParams});
405
406 console.log(searchParams.toString());
407 //=> 'key=a&key=b'
408 ```
409 */
410 searchParams?: string | Record<string, string | number | boolean | null | undefined> | URLSearchParams;
411 /**
412 An instance of [`CacheableLookup`](https://github.com/szmarczak/cacheable-lookup) used for making DNS lookups.
413 Useful when making lots of requests to different *public* hostnames.
414
415 `CacheableLookup` uses `dns.resolver4(..)` and `dns.resolver6(...)` under the hood and fall backs to `dns.lookup(...)` when the first two fail, which may lead to additional delay.
416
417 __Note__: This should stay disabled when making requests to internal hostnames such as `localhost`, `database.local` etc.
418
419 @default false
420 */
421 dnsCache?: CacheableLookup | boolean;
422 /**
423 User data. In contrast to other options, `context` is not enumerable.
424
425 __Note__: The object is never merged, it's just passed through.
426 Got will not modify the object in any way.
427
428 @example
429 ```
430 const got = require('got');
431
432 const instance = got.extend({
433 hooks: {
434 beforeRequest: [
435 options => {
436 if (!options.context || !options.context.token) {
437 throw new Error('Token required');
438 }
439
440 options.headers.token = options.context.token;
441 }
442 ]
443 }
444 });
445
446 (async () => {
447 const context = {
448 token: 'secret'
449 };
450
451 const response = await instance('https://httpbin.org/headers', {context});
452
453 // Let's see the headers
454 console.log(response.body);
455 })();
456 ```
457 */
458 context?: Record<string, unknown>;
459 /**
460 Hooks allow modifications during the request lifecycle.
461 Hook functions may be async and are run serially.
462 */
463 hooks?: Hooks;
464 /**
465 Defines if redirect responses should be followed automatically.
466
467 Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`.
468 This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4).
469
470 @default true
471 */
472 followRedirect?: boolean;
473 /**
474 If exceeded, the request will be aborted and a `MaxRedirectsError` will be thrown.
475
476 @default 10
477 */
478 maxRedirects?: number;
479 /**
480 A cache adapter instance for storing cached response data.
481
482 @default false
483 */
484 cache?: string | CacheableRequest.StorageAdapter | false;
485 /**
486 Determines if a `got.HTTPError` is thrown for unsuccessful responses.
487
488 If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing.
489 This may be useful if you are checking for resource availability and are expecting error responses.
490
491 @default true
492 */
493 throwHttpErrors?: boolean;
494 username?: string;
495 password?: string;
496 /**
497 If set to `true`, Got will additionally accept HTTP2 requests.
498
499 It will choose either HTTP/1.1 or HTTP/2 depending on the ALPN protocol.
500
501 __Note__: Overriding `options.request` will disable HTTP2 support.
502
503 __Note__: This option will default to `true` in the next upcoming major release.
504
505 @default false
506
507 @example
508 ```
509 const got = require('got');
510
511 (async () => {
512 const {headers} = await got('https://nghttp2.org/httpbin/anything', {http2: true});
513 console.log(headers.via);
514 //=> '2 nghttpx'
515 })();
516 ```
517 */
518 http2?: boolean;
519 /**
520 Set this to `true` to allow sending body for the `GET` method.
521 However, the [HTTP/2 specification](https://tools.ietf.org/html/rfc7540#section-8.1.3) says that `An HTTP GET request includes request header fields and no payload body`, therefore when using the HTTP/2 protocol this option will have no effect.
522 This option is only meant to interact with non-compliant servers when you have no other choice.
523
524 __Note__: The [RFC 7321](https://tools.ietf.org/html/rfc7231#section-4.3.1) doesn't specify any particular behavior for the GET method having a payload, therefore __it's considered an [anti-pattern](https://en.wikipedia.org/wiki/Anti-pattern)__.
525
526 @default false
527 */
528 allowGetBody?: boolean;
529 lookup?: CacheableLookup['lookup'];
530 /**
531 Request headers.
532
533 Existing headers will be overwritten. Headers set to `undefined` will be omitted.
534
535 @default {}
536 */
537 headers?: Headers;
538 /**
539 By default, redirects will use [method rewriting](https://tools.ietf.org/html/rfc7231#section-6.4).
540 For example, when sending a POST request and receiving a `302`, it will resend the body to the new location using the same HTTP method (`POST` in this case).
541
542 @default true
543 */
544 methodRewriting?: boolean;
545 /**
546 Indicates which DNS record family to use.
547
548 Values:
549 - `auto`: IPv4 (if present) or IPv6
550 - `ipv4`: Only IPv4
551 - `ipv6`: Only IPv6
552
553 __Note__: If you are using the undocumented option `family`, `dnsLookupIpVersion` will override it.
554
555 @default 'auto'
556 */
557 dnsLookupIpVersion?: DnsLookupIpVersion;
558 /**
559 A function used to parse JSON responses.
560
561 @example
562 ```
563 const got = require('got');
564 const Bourne = require('@hapi/bourne');
565
566 (async () => {
567 const parsed = await got('https://example.com', {
568 parseJson: text => Bourne.parse(text)
569 }).json();
570
571 console.log(parsed);
572 })();
573 ```
574 */
575 parseJson?: ParseJsonFunction;
576 /**
577 A function used to stringify the body of JSON requests.
578
579 @example
580 ```
581 const got = require('got');
582
583 (async () => {
584 await got.post('https://example.com', {
585 stringifyJson: object => JSON.stringify(object, (key, value) => {
586 if (key.startsWith('_')) {
587 return;
588 }
589
590 return value;
591 }),
592 json: {
593 some: 'payload',
594 _ignoreMe: 1234
595 }
596 });
597 })();
598 ```
599
600 @example
601 ```
602 const got = require('got');
603
604 (async () => {
605 await got.post('https://example.com', {
606 stringifyJson: object => JSON.stringify(object, (key, value) => {
607 if (typeof value === 'number') {
608 return value.toString();
609 }
610
611 return value;
612 }),
613 json: {
614 some: 'payload',
615 number: 1
616 }
617 });
618 })();
619 ```
620 */
621 stringifyJson?: StringifyJsonFunction;
622 /**
623 An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
624
625 Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
626
627 The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value.
628 The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
629
630 By default, it retries *only* on the specified methods, status codes, and on these network errors:
631
632 - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
633 - `ECONNRESET`: Connection was forcibly closed by a peer.
634 - `EADDRINUSE`: Could not bind to any free port.
635 - `ECONNREFUSED`: Connection was refused by the server.
636 - `EPIPE`: The remote side of the stream being written has been closed.
637 - `ENOTFOUND`: Couldn't resolve the hostname to an IP address.
638 - `ENETUNREACH`: No internet connection.
639 - `EAI_AGAIN`: DNS lookup timed out.
640
641 __Note__: If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.
642 __Note__: If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
643 */
644 retry?: Partial<RequiredRetryOptions> | number;
645 /**
646 The IP address used to send the request from.
647 */
648 localAddress?: string;
649 socketPath?: string;
650 /**
651 The HTTP method used to make the request.
652
653 @default 'GET'
654 */
655 method?: Method;
656 createConnection?: (options: http.RequestOptions, oncreate: (error: Error, socket: Socket) => void) => Socket;
657 cacheOptions?: CacheOptions;
658 /**
659 If set to `false`, all invalid SSL certificates will be ignored and no error will be thrown.
660
661 If set to `true`, it will throw an error whenever an invalid SSL certificate is detected.
662
663 We strongly recommend to have this set to `true` for security reasons.
664
665 @default true
666
667 @example
668 ```
669 const got = require('got');
670
671 (async () => {
672 // Correct:
673 await got('https://example.com', {rejectUnauthorized: true});
674
675 // You can disable it when developing an HTTPS app:
676 await got('https://localhost', {rejectUnauthorized: false});
677
678 // Never do this:
679 await got('https://example.com', {rejectUnauthorized: false});
680 })();
681 ```
682 */
683 rejectUnauthorized?: boolean;
684 /**
685 Options for the advanced HTTPS API.
686 */
687 https?: HTTPSOptions;
688}
689export interface Options extends PromiseOnly.Options, PlainOptions {
690}
691export interface HTTPSOptions {
692 rejectUnauthorized?: https.RequestOptions['rejectUnauthorized'];
693 checkServerIdentity?: CheckServerIdentityFunction;
694 /**
695 Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)).
696
697 @example
698 ```
699 // Single Certificate Authority
700 got('https://example.com', {
701 https: {
702 certificateAuthority: fs.readFileSync('./my_ca.pem')
703 }
704 });
705 ```
706 */
707 certificateAuthority?: SecureContextOptions['ca'];
708 /**
709 Private keys in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.
710
711 [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) allows the option of private keys being encrypted.
712 Encrypted keys will be decrypted with `options.https.passphrase`.
713
714 Multiple keys with different passphrases can be provided as an array of `{pem: <string | Buffer>, passphrase: <string>}`
715 */
716 key?: SecureContextOptions['key'];
717 /**
718 [Certificate chains](https://en.wikipedia.org/wiki/X.509#Certificate_chains_and_cross-certification) in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format.
719
720 One cert chain should be provided per private key (`options.https.key`).
721
722 When providing multiple cert chains, they do not have to be in the same order as their private keys in `options.https.key`.
723
724 If the intermediate certificates are not provided, the peer will not be able to validate the certificate, and the handshake will fail.
725 */
726 certificate?: SecureContextOptions['cert'];
727 /**
728 The passphrase to decrypt the `options.https.key` (if different keys have different passphrases refer to `options.https.key` documentation).
729 */
730 passphrase?: SecureContextOptions['passphrase'];
731 pfx?: SecureContextOptions['pfx'];
732}
733interface NormalizedPlainOptions extends PlainOptions {
734 method: Method;
735 url: URL;
736 timeout: Delays;
737 prefixUrl: string;
738 ignoreInvalidCookies: boolean;
739 decompress: boolean;
740 searchParams?: URLSearchParams;
741 cookieJar?: PromiseCookieJar;
742 headers: Headers;
743 context: Record<string, unknown>;
744 hooks: Required<Hooks>;
745 followRedirect: boolean;
746 maxRedirects: number;
747 cache?: string | CacheableRequest.StorageAdapter;
748 throwHttpErrors: boolean;
749 dnsCache?: CacheableLookup;
750 http2: boolean;
751 allowGetBody: boolean;
752 rejectUnauthorized: boolean;
753 lookup?: CacheableLookup['lookup'];
754 methodRewriting: boolean;
755 username: string;
756 password: string;
757 parseJson: ParseJsonFunction;
758 stringifyJson: StringifyJsonFunction;
759 retry: RequiredRetryOptions;
760 cacheOptions: CacheOptions;
761 [kRequest]: HttpRequestFunction;
762 [kIsNormalizedAlready]?: boolean;
763}
764export interface NormalizedOptions extends PromiseOnly.NormalizedOptions, NormalizedPlainOptions {
765}
766interface PlainDefaults {
767 timeout: Delays;
768 prefixUrl: string;
769 method: Method;
770 ignoreInvalidCookies: boolean;
771 decompress: boolean;
772 context: Record<string, unknown>;
773 cookieJar?: PromiseCookieJar | ToughCookieJar;
774 dnsCache?: CacheableLookup;
775 headers: Headers;
776 hooks: Required<Hooks>;
777 followRedirect: boolean;
778 maxRedirects: number;
779 cache?: string | CacheableRequest.StorageAdapter;
780 throwHttpErrors: boolean;
781 http2: boolean;
782 allowGetBody: boolean;
783 https?: HTTPSOptions;
784 methodRewriting: boolean;
785 parseJson: ParseJsonFunction;
786 stringifyJson: StringifyJsonFunction;
787 retry: RequiredRetryOptions;
788 agent?: Agents | false;
789 request?: RequestFunction;
790 searchParams?: URLSearchParams;
791 lookup?: CacheableLookup['lookup'];
792 localAddress?: string;
793 createConnection?: Options['createConnection'];
794 cacheOptions: CacheOptions;
795}
796export interface Defaults extends PromiseOnly.Defaults, PlainDefaults {
797}
798export interface Progress {
799 percent: number;
800 transferred: number;
801 total?: number;
802}
803export interface PlainResponse extends IncomingMessageWithTimings {
804 /**
805 The original request URL.
806 */
807 requestUrl: string;
808 /**
809 The redirect URLs.
810 */
811 redirectUrls: string[];
812 /**
813 - `options` - The Got options that were set on this request.
814
815 __Note__: This is not a [http.ClientRequest](https://nodejs.org/api/http.html#http_class_http_clientrequest).
816 */
817 request: Request;
818 /**
819 The remote IP address.
820
821 This is hopefully a temporary limitation, see [lukechilds/cacheable-request#86](https://github.com/lukechilds/cacheable-request/issues/86).
822
823 __Note__: Not available when the response is cached.
824 */
825 ip?: string;
826 /**
827 Whether the response was retrieved from the cache.
828 */
829 isFromCache: boolean;
830 /**
831 The status code of the response.
832 */
833 statusCode: number;
834 /**
835 The request URL or the final URL after redirects.
836 */
837 url: string;
838 /**
839 The object contains the following properties:
840
841 - `start` - Time when the request started.
842 - `socket` - Time when a socket was assigned to the request.
843 - `lookup` - Time when the DNS lookup finished.
844 - `connect` - Time when the socket successfully connected.
845 - `secureConnect` - Time when the socket securely connected.
846 - `upload` - Time when the request finished uploading.
847 - `response` - Time when the request fired `response` event.
848 - `end` - Time when the response fired `end` event.
849 - `error` - Time when the request fired `error` event.
850 - `abort` - Time when the request fired `abort` event.
851 - `phases`
852 - `wait` - `timings.socket - timings.start`
853 - `dns` - `timings.lookup - timings.socket`
854 - `tcp` - `timings.connect - timings.lookup`
855 - `tls` - `timings.secureConnect - timings.connect`
856 - `request` - `timings.upload - (timings.secureConnect || timings.connect)`
857 - `firstByte` - `timings.response - timings.upload`
858 - `download` - `timings.end - timings.response`
859 - `total` - `(timings.end || timings.error || timings.abort) - timings.start`
860
861 If something has not been measured yet, it will be `undefined`.
862
863 __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
864 */
865 timings: Timings;
866 /**
867 The number of times the request was retried.
868 */
869 retryCount: number;
870 /**
871 The raw result of the request.
872 */
873 rawBody?: Buffer;
874 /**
875 The result of the request.
876 */
877 body?: unknown;
878}
879export interface Response<T = unknown> extends PlainResponse {
880 /**
881 The result of the request.
882 */
883 body: T;
884 /**
885 The raw result of the request.
886 */
887 rawBody: Buffer;
888}
889export interface RequestEvents<T> {
890 /**
891 `request` event to get the request object of the request.
892
893 __Tip__: You can use `request` event to abort requests.
894
895 @example
896 ```
897 got.stream('https://github.com')
898 .on('request', request => setTimeout(() => request.destroy(), 50));
899 ```
900 */
901 on: ((name: 'request', listener: (request: http.ClientRequest) => void) => T)
902 /**
903 The `response` event to get the response object of the final request.
904 */
905 & (<R extends Response>(name: 'response', listener: (response: R) => void) => T)
906 /**
907 The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
908 */
909 & (<R extends Response, N extends NormalizedOptions>(name: 'redirect', listener: (response: R, nextOptions: N) => void) => T)
910 /**
911 Progress events for uploading (sending a request) and downloading (receiving a response).
912 The `progress` argument is an object like:
913
914 ```js
915 {
916 percent: 0.1,
917 transferred: 1024,
918 total: 10240
919 }
920 ```
921
922 If the `content-length` header is missing, `total` will be `undefined`.
923
924 @example
925 ```js
926 (async () => {
927 const response = await got('https://sindresorhus.com')
928 .on('downloadProgress', progress => {
929 // Report download progress
930 })
931 .on('uploadProgress', progress => {
932 // Report upload progress
933 });
934
935 console.log(response);
936 })();
937 ```
938 */
939 & ((name: 'uploadProgress' | 'downloadProgress', listener: (progress: Progress) => void) => T)
940 /**
941 To enable retrying on a Got stream, it is required to have a `retry` handler attached.
942
943 When this event is emitted, you should reset the stream you were writing to and prepare the body again.
944
945 See `got.options.retry` for more information.
946 */
947 & ((name: 'retry', listener: (retryCount: number, error: RequestError) => void) => T);
948}
949export declare const setNonEnumerableProperties: (sources: Array<Options | Defaults | undefined>, to: Options) => void;
950/**
951An error to be thrown when a request fails.
952Contains a `code` property with error class code, like `ECONNREFUSED`.
953*/
954export declare class RequestError extends Error {
955 code?: string;
956 stack: string;
957 readonly options: NormalizedOptions;
958 readonly response?: Response;
959 readonly request?: Request;
960 readonly timings?: Timings;
961 constructor(message: string, error: Partial<Error & {
962 code?: string;
963 }>, self: Request | NormalizedOptions);
964}
965/**
966An error to be thrown when the server redirects you more than ten times.
967Includes a `response` property.
968*/
969export declare class MaxRedirectsError extends RequestError {
970 readonly response: Response;
971 readonly request: Request;
972 readonly timings: Timings;
973 constructor(request: Request);
974}
975/**
976An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.
977Includes a `response` property.
978*/
979export declare class HTTPError extends RequestError {
980 readonly response: Response;
981 readonly request: Request;
982 readonly timings: Timings;
983 constructor(response: Response);
984}
985/**
986An error to be thrown when a cache method fails.
987For example, if the database goes down or there's a filesystem error.
988*/
989export declare class CacheError extends RequestError {
990 readonly request: Request;
991 constructor(error: Error, request: Request);
992}
993/**
994An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
995*/
996export declare class UploadError extends RequestError {
997 readonly request: Request;
998 constructor(error: Error, request: Request);
999}
1000/**
1001An error to be thrown when the request is aborted due to a timeout.
1002Includes an `event` and `timings` property.
1003*/
1004export declare class TimeoutError extends RequestError {
1005 readonly request: Request;
1006 readonly timings: Timings;
1007 readonly event: string;
1008 constructor(error: TimedOutTimeoutError, timings: Timings, request: Request);
1009}
1010/**
1011An error to be thrown when reading from response stream fails.
1012*/
1013export declare class ReadError extends RequestError {
1014 readonly request: Request;
1015 readonly response: Response;
1016 readonly timings: Timings;
1017 constructor(error: Error, request: Request);
1018}
1019/**
1020An error to be thrown when given an unsupported protocol.
1021*/
1022export declare class UnsupportedProtocolError extends RequestError {
1023 constructor(options: NormalizedOptions);
1024}
1025export default class Request extends Duplex implements RequestEvents<Request> {
1026 ['constructor']: typeof Request;
1027 [kUnproxyEvents]: () => void;
1028 _cannotHaveBody: boolean;
1029 [kDownloadedSize]: number;
1030 [kUploadedSize]: number;
1031 [kStopReading]: boolean;
1032 [kTriggerRead]: boolean;
1033 [kBody]: Options['body'];
1034 [kJobs]: Array<() => void>;
1035 [kRetryTimeout]?: NodeJS.Timeout;
1036 [kBodySize]?: number;
1037 [kServerResponsesPiped]: Set<ServerResponse>;
1038 [kIsFromCache]?: boolean;
1039 [kStartedReading]?: boolean;
1040 [kCancelTimeouts]?: () => void;
1041 [kResponseSize]?: number;
1042 [kResponse]?: IncomingMessageWithTimings;
1043 [kOriginalResponse]?: IncomingMessageWithTimings;
1044 [kRequest]?: ClientRequest;
1045 _noPipe?: boolean;
1046 _progressCallbacks: Array<() => void>;
1047 options: NormalizedOptions;
1048 requestUrl: string;
1049 requestInitialized: boolean;
1050 redirects: string[];
1051 retryCount: number;
1052 constructor(url: string | URL | undefined, options?: Options, defaults?: Defaults);
1053 static normalizeArguments(url?: string | URL, options?: Options, defaults?: Defaults): NormalizedOptions;
1054 _lockWrite(): void;
1055 _unlockWrite(): void;
1056 _finalizeBody(): Promise<void>;
1057 _onResponseBase(response: IncomingMessageWithTimings): Promise<void>;
1058 _onResponse(response: IncomingMessageWithTimings): Promise<void>;
1059 _onRequest(request: ClientRequest): void;
1060 _createCacheableRequest(url: URL, options: RequestOptions): Promise<ClientRequest | ResponseLike>;
1061 _makeRequest(): Promise<void>;
1062 _error(error: RequestError): Promise<void>;
1063 _beforeError(error: Error): void;
1064 _read(): void;
1065 _write(chunk: any, encoding: string | undefined, callback: (error?: Error | null) => void): void;
1066 _writeRequest(chunk: any, encoding: BufferEncoding | undefined, callback: (error?: Error | null) => void): void;
1067 _final(callback: (error?: Error | null) => void): void;
1068 _destroy(error: Error | null, callback: (error: Error | null) => void): void;
1069 get _isAboutToError(): boolean;
1070 /**
1071 The remote IP address.
1072 */
1073 get ip(): string | undefined;
1074 /**
1075 Indicates whether the request has been aborted or not.
1076 */
1077 get aborted(): boolean;
1078 get socket(): Socket | undefined;
1079 /**
1080 Progress event for downloading (receiving a response).
1081 */
1082 get downloadProgress(): Progress;
1083 /**
1084 Progress event for uploading (sending a request).
1085 */
1086 get uploadProgress(): Progress;
1087 /**
1088 The object contains the following properties:
1089
1090 - `start` - Time when the request started.
1091 - `socket` - Time when a socket was assigned to the request.
1092 - `lookup` - Time when the DNS lookup finished.
1093 - `connect` - Time when the socket successfully connected.
1094 - `secureConnect` - Time when the socket securely connected.
1095 - `upload` - Time when the request finished uploading.
1096 - `response` - Time when the request fired `response` event.
1097 - `end` - Time when the response fired `end` event.
1098 - `error` - Time when the request fired `error` event.
1099 - `abort` - Time when the request fired `abort` event.
1100 - `phases`
1101 - `wait` - `timings.socket - timings.start`
1102 - `dns` - `timings.lookup - timings.socket`
1103 - `tcp` - `timings.connect - timings.lookup`
1104 - `tls` - `timings.secureConnect - timings.connect`
1105 - `request` - `timings.upload - (timings.secureConnect || timings.connect)`
1106 - `firstByte` - `timings.response - timings.upload`
1107 - `download` - `timings.end - timings.response`
1108 - `total` - `(timings.end || timings.error || timings.abort) - timings.start`
1109
1110 If something has not been measured yet, it will be `undefined`.
1111
1112 __Note__: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
1113 */
1114 get timings(): Timings | undefined;
1115 /**
1116 Whether the response was retrieved from the cache.
1117 */
1118 get isFromCache(): boolean | undefined;
1119 pipe<T extends NodeJS.WritableStream>(destination: T, options?: {
1120 end?: boolean;
1121 }): T;
1122 unpipe<T extends NodeJS.WritableStream>(destination: T): this;
1123}
1124export {};
1125
\No newline at end of file