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