forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptions.ts
More file actions
2982 lines (2378 loc) · 85.2 KB
/
Copy pathoptions.ts
File metadata and controls
2982 lines (2378 loc) · 85.2 KB
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 process from 'node:process';
import type {Buffer} from 'node:buffer';
import {promisify, inspect, type InspectOptions} from 'node:util';
import {checkServerIdentity, type SecureContextOptions, type DetailedPeerCertificate} from 'node:tls';
// DO NOT use destructuring for `https.request` and `http.request` as it's not compatible with `nock`.
import https, {
type RequestOptions as HttpsRequestOptions,
type Agent as HttpsAgent,
} from 'node:https';
import http, {
type Agent as HttpAgent,
type ClientRequest,
} from 'node:http';
import type {Readable} from 'node:stream';
import type {Socket, LookupFunction} from 'node:net';
import is, {assert} from '@sindresorhus/is';
import lowercaseKeys from 'lowercase-keys';
import CacheableLookup from 'cacheable-lookup';
import http2wrapper, {type ClientHttp2Session} from 'http2-wrapper';
import {isFormData, type FormDataLike} from 'form-data-encoder';
import type {KeyvStoreAdapter} from 'keyv';
import type KeyvType from 'keyv';
import type ResponseLike from 'responselike';
import type {CancelableRequest} from '../as-promise/types.js';
import type {IncomingMessageWithTimings} from './utils/timer.js';
import parseLinkHeader from './parse-link-header.js';
import type {PlainResponse, Response} from './response.js';
import type {RequestError} from './errors.js';
import type {Delays} from './timed-out.js';
type StorageAdapter = KeyvStoreAdapter | KeyvType | Map<any, any>;
type Promisable<T> = T | Promise<T>;
const [major, minor] = process.versions.node.split('.').map(Number) as [number, number, number];
export type DnsLookupIpVersion = undefined | 4 | 6;
type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
export type NativeRequestOptions = HttpsRequestOptions & CacheOptions & {checkServerIdentity?: CheckServerIdentityFunction};
type AcceptableResponse = IncomingMessageWithTimings | ResponseLike;
type AcceptableRequestResult = Promisable<AcceptableResponse | ClientRequest> | undefined;
export type RequestFunction = (url: URL, options: NativeRequestOptions, callback?: (response: AcceptableResponse) => void) => AcceptableRequestResult;
export type Agents = {
http?: HttpAgent | false;
https?: HttpsAgent | false;
http2?: unknown | false;
};
export type Headers = Record<string, string | string[] | undefined>;
export type ToughCookieJar = {
getCookieString: ((currentUrl: string, options: Record<string, unknown>, callback: (error: Error | null, cookies: string) => void) => void) // eslint-disable-line @typescript-eslint/ban-types
& ((url: string, callback: (error: Error | null, cookieHeader: string) => void) => void); // eslint-disable-line @typescript-eslint/ban-types
setCookie: ((cookieOrString: unknown, currentUrl: string, options: Record<string, unknown>, callback: (error: Error | null, cookie: unknown) => void) => void) // eslint-disable-line @typescript-eslint/ban-types
& ((rawCookie: string, url: string, callback: (error: Error | null, result: unknown) => void) => void); // eslint-disable-line @typescript-eslint/ban-types
};
export type PromiseCookieJar = {
getCookieString: (url: string) => Promise<string>;
setCookie: (rawCookie: string, url: string) => Promise<unknown>;
};
/**
Utility type to override specific properties in a type.
Uses `Omit` to remove properties before adding them back to ensure proper type replacement rather than intersection, which handles edge cases with optional/required properties correctly.
*/
type OverrideProperties<T, U> = Omit<T, keyof U> & U;
/**
Represents the runtime state of Options as seen by hooks after normalization.
Some Options properties accept multiple input types but are normalized to a single type internally by the Options class setters. This type reflects the actual runtime types that hooks receive, ensuring type safety when accessing options within hook functions.
*/
export type NormalizedOptions = OverrideProperties<Options, {
// The URL is always normalized to a URL instance (or undefined) by the time hooks execute.
url: URL | undefined;
// When set to `true`, dnsCache is normalized to a CacheableLookup instance. When set to `false`, it becomes `undefined`.
dnsCache: CacheableLookup | undefined;
// When set to `true`, cache is normalized to the global cache Map. When set to `false`, it becomes `undefined`. Strings and other values are wrapped/processed into a StorageAdapter.
cache: StorageAdapter | undefined;
// The prefix URL is always normalized to a string.
prefixUrl: string;
}>;
export type InitHook = (init: OptionsInit, self: Options) => void;
export type BeforeRequestHookContext = {
/**
The current retry count.
It will be `0` for the initial request and increment for each retry.
*/
retryCount: number;
};
export type BeforeRequestHook = (options: NormalizedOptions, context: BeforeRequestHookContext) => Promisable<void | Response | ResponseLike>;
export type BeforeRedirectHook = (updatedOptions: NormalizedOptions, plainResponse: PlainResponse) => Promisable<void>;
export type BeforeErrorHook = (error: RequestError) => Promisable<Error>;
export type BeforeRetryHook = (error: RequestError, retryCount: number) => Promisable<void>;
export type BeforeCacheHook = (response: PlainResponse) => false | void;
export type AfterResponseHook<ResponseType = unknown> = (response: Response<ResponseType>, retryWithMergedOptions: (options: OptionsInit) => never) => Promisable<Response | CancelableRequest<Response>>;
/**
All available hooks of Got.
*/
export type Hooks = {
/**
Called with the plain request options, right before their normalization.
The second argument represents the current `Options` instance.
@default []
**Note:**
> - This hook must be synchronous.
**Note:**
> - This is called every time options are merged.
**Note:**
> - The `options` object may not have the `url` property. To modify it, use a `beforeRequest` hook instead.
**Note:**
> - This hook is called when a new instance of `Options` is created.
> - Do not confuse this with the creation of `Request` or `got(…)`.
**Note:**
> - When using `got(url)` or `got(url, undefined, defaults)` this hook will **not** be called.
This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
For example, this can be used to fix typos to migrate from older versions faster.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
init: [
plain => {
if ('followRedirects' in plain) {
plain.followRedirect = plain.followRedirects;
delete plain.followRedirects;
}
}
]
}
});
// Normally, the following would throw:
const response = await instance(
'https://example.com',
{
followRedirects: true
}
);
// There is no option named `followRedirects`, but we correct it in an `init` hook.
```
Or you can create your own option and store it in a context:
```
import got from 'got';
const instance = got.extend({
hooks: {
init: [
(plain, options) => {
if ('secret' in plain) {
options.context.secret = plain.secret;
delete plain.secret;
}
}
],
beforeRequest: [
options => {
options.headers.secret = options.context.secret;
}
]
}
});
const {headers} = await instance(
'https://httpbin.org/anything',
{
secret: 'passphrase'
}
).json();
console.log(headers.Secret);
//=> 'passphrase'
```
*/
init: InitHook[];
/**
Called right before making the request with `options.createNativeRequestOptions()`.
The second argument is a context object containing request state information.
This hook is especially useful in conjunction with `got.extend()` when you want to sign your request.
@default []
**Note:**
> - Got will make no further changes to the request before it is sent.
**Note:**
> - Changing `options.json` or `options.form` has no effect on the request. You should change `options.body` instead. If needed, update the `options.headers` accordingly.
@example
```
import got from 'got';
const response = await got.post(
'https://httpbin.org/anything',
{
json: {payload: 'old'},
hooks: {
beforeRequest: [
(options, context) => {
options.body = JSON.stringify({payload: 'new'});
options.headers['content-length'] = options.body.length.toString();
}
]
}
}
);
```
**Example using `context.retryCount`:**
```
import got from 'got';
await got('https://httpbin.org/status/500', {
retry: {
limit: 2
},
hooks: {
beforeRequest: [
(options, context) => {
// Only log on the initial request, not on retries
if (context.retryCount === 0) {
console.log('Making initial request');
}
}
]
}
});
```
**Tip:**
> - You can indirectly override the `request` function by early returning a [`ClientRequest`-like](https://nodejs.org/api/http.html#http_class_http_clientrequest) instance or a [`IncomingMessage`-like](https://nodejs.org/api/http.html#http_class_http_incomingmessage) instance. This is very useful when creating a custom cache mechanism.
> - [Read more about this tip](https://github.com/sindresorhus/got/blob/main/documentation/cache.md#advanced-caching-mechanisms).
*/
beforeRequest: BeforeRequestHook[];
/**
The equivalent of `beforeRequest` but when redirecting.
@default []
**Tip:**
> - This is especially useful when you want to avoid dead sites.
@example
```
import got from 'got';
const response = await got('https://example.com', {
hooks: {
beforeRedirect: [
(options, response) => {
if (options.hostname === 'deadSite') {
options.hostname = 'fallbackSite';
}
}
]
}
});
```
*/
beforeRedirect: BeforeRedirectHook[];
/**
Called with a `RequestError` instance. The error is passed to the hook right before it's thrown.
This hook can return any `Error` instance, allowing you to:
- Return custom error classes for better error handling in your application
- Extend `RequestError` with additional properties
- Return plain `Error` instances when you don't need Got-specific error information
This is especially useful when you want to have more detailed errors or maintain backward compatibility with existing error handling code.
@default []
@example
```
import got from 'got';
// Modify and return the error
await got('https://api.github.com/repos/sindresorhus/got/commits', {
responseType: 'json',
hooks: {
beforeError: [
error => {
const {response} = error;
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode})`;
}
return error;
}
]
}
});
// Return a custom error class
class CustomAPIError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'CustomAPIError';
this.statusCode = statusCode;
}
}
await got('https://api.example.com/endpoint', {
hooks: {
beforeError: [
error => {
// Return a custom error for backward compatibility with your application
return new CustomAPIError(
error.message,
error.response?.statusCode
);
}
]
}
});
```
*/
beforeError: BeforeErrorHook[];
/**
The equivalent of `beforeError` but when retrying. Additionally, there is a second argument `retryCount`, the current retry number.
@default []
**Note:**
> - When using the Stream API, this hook is ignored.
**Note:**
> - When retrying, the `beforeRequest` hook is called afterwards.
**Note:**
> - If no retry occurs, the `beforeError` hook is called instead.
This hook is especially useful when you want to retrieve the cause of a retry.
@example
```
import got from 'got';
await got('https://httpbin.org/status/500', {
hooks: {
beforeRetry: [
(error, retryCount) => {
console.log(`Retrying [${retryCount}]: ${error.code}`);
// Retrying [1]: ERR_NON_2XX_3XX_RESPONSE
}
]
}
});
```
*/
beforeRetry: BeforeRetryHook[];
/**
Called right before the response is cached. Allows you to control caching behavior by directly modifying the response or preventing caching.
This is especially useful when you want to prevent caching of specific responses or modify cache headers.
@default []
**Return value:**
> - `false` - Prevent caching (remaining hooks are skipped)
> - `void`/`undefined` - Use default caching behavior (mutations take effect)
**Modifying the response:**
> - Hooks can directly mutate response properties like `headers`, `statusCode`, and `statusMessage`
> - Mutations to `response.headers` affect how the caching layer decides whether to cache the response and for how long
> - Changes are applied to what gets cached
**Note:**
> - This hook is only called when the `cache` option is enabled.
**Note:**
> - This hook must be synchronous. It cannot return a Promise. If you need async logic to determine caching behavior, use a `beforeRequest` hook instead.
**Note:**
> - When returning `false`, remaining hooks are skipped and the response will not be cached.
**Note:**
> - Returning anything other than `false` or `undefined` will throw a TypeError.
**Note:**
> - If a hook throws an error, it will be propagated and the request will fail. This is consistent with how other hooks in Got handle errors.
**Note:**
> - At this stage, the response body has not been read yet - it's still a stream. Properties like `response.body` and `response.rawBody` are not available. You can only inspect/modify response headers and status code.
@example
```
import got from 'got';
// Simple: Don't cache errors
const instance = got.extend({
cache: new Map(),
hooks: {
beforeCache: [
(response) => response.statusCode >= 400 ? false : undefined
]
}
});
// Advanced: Modify headers for fine control
const instance2 = got.extend({
cache: new Map(),
hooks: {
beforeCache: [
(response) => {
// Force caching with explicit duration
// Mutations work directly - no need to return
response.headers['cache-control'] = 'public, max-age=3600';
}
]
}
});
await instance('https://example.com');
```
*/
beforeCache: BeforeCacheHook[];
/**
Each function should return the response. This is especially useful when you want to refresh an access token.
@default []
**Note:**
> - When using the Stream API, this hook is ignored.
**Note:**
> - Calling the `retryWithMergedOptions` function will trigger `beforeRetry` hooks. By default, remaining `afterResponse` hooks are removed to prevent duplicate execution. To preserve remaining hooks on retry, set `preserveHooks: true` in the options passed to `retryWithMergedOptions`. In case of an error, `beforeRetry` hooks will be called instead.
Meanwhile the `init`, `beforeRequest` , `beforeRedirect` as well as already executed `afterResponse` hooks will be skipped.
**Note:**
> - To preserve remaining `afterResponse` hooks after calling `retryWithMergedOptions`, set `preserveHooks: true` in the options passed to `retryWithMergedOptions`. This is useful when you want hooks to run on retried requests.
**Warning:**
> - Be cautious when using `preserveHooks: true`. If a hook unconditionally calls `retryWithMergedOptions` with `preserveHooks: true`, it will create an infinite retry loop. Always ensure hooks have proper conditional logic to avoid infinite retries.
@example
```
import got from 'got';
const instance = got.extend({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
// Unauthorized
if (response.statusCode === 401) {
// Refresh the access token
const updatedOptions = {
headers: {
token: getNewToken()
}
};
// Update the defaults
instance.defaults.options.merge(updatedOptions);
// Make a new retry
return retryWithMergedOptions(updatedOptions);
}
// No changes otherwise
return response;
}
],
beforeRetry: [
error => {
// This will be called on `retryWithMergedOptions(...)`
}
]
},
mutableDefaults: true
});
```
@example
```
// Example with preserveHooks
import got from 'got';
const instance = got.extend({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
authorization: getNewToken()
},
preserveHooks: true // Keep remaining hooks
});
}
return response;
},
(response) => {
// This hook will run on the retried request
// (the original request is interrupted when the first hook triggers a retry)
console.log('Response received:', response.statusCode);
return response;
}
]
}
});
```
*/
afterResponse: AfterResponseHook[];
};
export type ParseJsonFunction = (text: string) => unknown;
export type StringifyJsonFunction = (object: unknown) => string;
/**
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';
export type RetryObject = {
attemptCount: number;
retryOptions: RetryOptions;
error: RequestError;
computedValue: number;
retryAfter?: number;
};
export type RetryFunction = (retryObject: RetryObject) => Promisable<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).
The `enforceRetryRules` property is a `boolean` that, when set to `true`, enforces the `limit`, `methods`, `statusCodes`, and `errorCodes` options before calling `calculateDelay`. Your `calculateDelay` function is only invoked when a retry is allowed based on these criteria. When `false` (default), `calculateDelay` receives the computed value but can override all retry logic.
__Note:__ When `enforceRetryRules` is `false`, you must check `computedValue` in your `calculateDelay` function to respect the default retry logic. When `true`, the retry rules are enforced automatically.
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:__ Got does not retry on `POST` by default.
__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 type RetryOptions = {
limit: number;
methods: Method[];
statusCodes: number[];
errorCodes: string[];
calculateDelay: RetryFunction;
backoffLimit: number;
noise: number;
maxRetryAfter?: number;
enforceRetryRules?: boolean;
};
export type CreateConnectionFunction = (options: NativeRequestOptions, oncreate: (error: NodeJS.ErrnoException, socket: Socket) => void) => Socket;
export type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => NodeJS.ErrnoException | void;
export type CacheOptions = {
shared?: boolean;
cacheHeuristic?: number;
immutableMinTimeToLive?: number;
ignoreCargoCult?: boolean;
};
type PfxObject = {
buffer: string | Buffer;
passphrase?: string | undefined;
};
type PfxType = string | Buffer | Array<string | Buffer | PfxObject> | undefined;
export type HttpsOptions = {
alpnProtocols?: string[];
// From `http.RequestOptions` and `tls.CommonConnectionOptions`
rejectUnauthorized?: NativeRequestOptions['rejectUnauthorized'];
// From `tls.ConnectionOptions`
checkServerIdentity?: CheckServerIdentityFunction;
/**
Server name for the [Server Name Indication (SNI)](https://en.wikipedia.org/wiki/Server_Name_Indication) TLS extension.
This is useful when requesting to servers that don't have a proper domain name but use a certificate with a known CN/SAN.
@example
```
import got from 'got';
// Request to IP address with specific servername for TLS
await got('https://192.168.1.100', {
https: {
serverName: 'example.com'
}
});
```
*/
serverName?: string;
// From `tls.SecureContextOptions`
/**
Override the default Certificate Authorities ([from Mozilla](https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport)).
@example
```
// Single Certificate Authority
await 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?: PfxType;
ciphers?: SecureContextOptions['ciphers'];
honorCipherOrder?: SecureContextOptions['honorCipherOrder'];
minVersion?: SecureContextOptions['minVersion'];
maxVersion?: SecureContextOptions['maxVersion'];
signatureAlgorithms?: SecureContextOptions['sigalgs'];
tlsSessionLifetime?: SecureContextOptions['sessionTimeout'];
dhparam?: SecureContextOptions['dhparam'];
ecdhCurve?: SecureContextOptions['ecdhCurve'];
certificateRevocationLists?: SecureContextOptions['crl'];
/**
Optionally affect the OpenSSL protocol behavior, which is not usually necessary. This should be used carefully if at all!
The value is a numeric bitmask of the `SSL_OP_*` options from OpenSSL.
For example, to allow connections to legacy servers that do not support secure renegotiation, you can use `crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT`.
@example
```
import crypto from 'node:crypto';
import got from 'got';
// Allow connections to servers with legacy renegotiation
await got('https://legacy-server.com', {
https: {
secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT
}
});
```
*/
secureOptions?: number;
};
export type PaginateData<BodyType, ElementType> = {
response: Response<BodyType>;
currentItems: ElementType[];
allItems: ElementType[];
};
export type FilterData<ElementType> = {
item: ElementType;
currentItems: ElementType[];
allItems: ElementType[];
};
/**
All options accepted by `got.paginate()`.
*/
export type PaginationOptions<ElementType, BodyType> = {
/**
A function that transform [`Response`](#response) into an array of items.
This is where you should do the parsing.
@default response => JSON.parse(response.body)
*/
transform?: (response: Response<BodyType>) => Promise<ElementType[]> | ElementType[];
/**
Checks whether the item should be emitted or not.
@default ({item, currentItems, allItems}) => true
*/
filter?: (data: FilterData<ElementType>) => boolean;
/**
The function takes an object with the following properties:
- `response` - The current response object.
- `currentItems` - Items from the current response.
- `allItems` - An empty array, unless `pagination.stackAllItems` is set to `true`, in which case, it's an array of the emitted items.
It should return an object representing Got options pointing to the next page. The options are merged automatically with the previous request, therefore the options returned `pagination.paginate(...)` must reflect changes only. If there are no more pages, `false` should be returned.
@example
```
import got from 'got';
const limit = 10;
const items = got.paginate('https://example.com/items', {
searchParams: {
limit,
offset: 0
},
pagination: {
paginate: ({response, currentItems}) => {
const previousSearchParams = response.request.options.searchParams;
const previousOffset = previousSearchParams.get('offset');
if (currentItems.length < limit) {
return false;
}
return {
searchParams: {
...previousSearchParams,
offset: Number(previousOffset) + limit,
}
};
}
}
});
console.log('Items from all pages:', items);
```
*/
paginate?: (data: PaginateData<BodyType, ElementType>) => OptionsInit | false;
/**
Checks whether the pagination should continue.
For example, if you need to stop **before** emitting an entry with some flag, you should use `({item}) => !item.flag`.
If you want to stop **after** emitting the entry, you should use
`({item, allItems}) => allItems.some(item => item.flag)` instead.
@default ({item, currentItems, allItems}) => true
*/
shouldContinue?: (data: FilterData<ElementType>) => boolean;
/**
The maximum amount of items that should be emitted.
@default Infinity
*/
countLimit?: number;
/**
Milliseconds to wait before the next request is triggered.
@default 0
*/
backoff?: number;
/**
The maximum amount of request that should be triggered.
Retries on failure are not counted towards this limit.
For example, it can be helpful during development to avoid an infinite number of requests.
@default 10000
*/
requestLimit?: number;
/**
Defines how the property `allItems` in `pagination.paginate`, `pagination.filter` and `pagination.shouldContinue` is managed.
By default, the property `allItems` is always an empty array. This setting can be helpful to save on memory usage when working with a large dataset.
When set to `true`, the property `allItems` is an array of the emitted items.
@default false
*/
stackAllItems?: boolean;
};
export type SearchParameters = Record<string, string | number | boolean | null | undefined>; // eslint-disable-line @typescript-eslint/ban-types
/**
Generic helper that wraps any assertion function to add context to error messages.
*/
function wrapAssertionWithContext(optionName: string, assertionFn: () => void): void {
try {
assertionFn();
} catch (error) {
if (error instanceof Error) {
error.message = `Option '${optionName}': ${error.message}`;
}
throw error;
}
}
/**
Helper function that wraps assert.any() to provide better error messages.
When assertion fails, it includes the option name in the error message.
*/
function assertAny(optionName: string, validators: any[], value: unknown): void {
wrapAssertionWithContext(optionName, () => {
assert.any(validators, value);
});
}
/**
Helper function that wraps assert.plainObject() to provide better error messages.
When assertion fails, it includes the option name in the error message.
*/
function assertPlainObject(optionName: string, value: unknown): void {
wrapAssertionWithContext(optionName, () => {
assert.plainObject(value);
});
}
function validateSearchParameters(searchParameters: Record<string, unknown>): asserts searchParameters is Record<string, string | number | boolean | null | undefined> { // eslint-disable-line @typescript-eslint/ban-types
// eslint-disable-next-line guard-for-in
for (const key in searchParameters) {
const value = searchParameters[key];
assertAny(`searchParams.${key}`, [is.string, is.number, is.boolean, is.null, is.undefined], value);
}
}
/**
All parsing methods supported by Got.
*/
export type ResponseType = 'json' | 'buffer' | 'text';
type OptionsToSkip =
'searchParameters' |
'followRedirects' |
'auth' |
'toJSON' |
'merge' |
'createNativeRequestOptions' |
'getRequestFunction' |
'getFallbackRequestFunction' |
'freeze';
export type InternalsType = Except<Options, OptionsToSkip>;
export type OptionsError = NodeJS.ErrnoException & {options?: Options};
export type OptionsInit =
Except<Partial<InternalsType>, 'hooks' | 'retry'>
& {
hooks?: Partial<Hooks>;
retry?: Partial<RetryOptions>;
preserveHooks?: boolean;
};
const globalCache = new Map();
let globalDnsCache: CacheableLookup;
const getGlobalDnsCache = (): CacheableLookup => {
if (globalDnsCache) {
return globalDnsCache;
}
globalDnsCache = new CacheableLookup();
return globalDnsCache;
};
// Detects and wraps QuickLRU v7+ instances to make them compatible with the StorageAdapter interface
const wrapQuickLruIfNeeded = (value: any): any => {
// Check if this is QuickLRU v7+ using Symbol.toStringTag and the evict method (added in v7)
if (value?.[Symbol.toStringTag] === 'QuickLRU' && typeof value.evict === 'function') {
// QuickLRU v7+ uses set(key, value, {maxAge: number}) but StorageAdapter expects set(key, value, ttl)
// Wrap it to translate the interface
return {
get(key: string) {
return value.get(key);
},
set(key: string, cacheValue: any, ttl?: number) {
if (ttl === undefined) {
value.set(key, cacheValue);
} else {
value.set(key, cacheValue, {maxAge: ttl});
}
return true;
},
delete(key: string) {
return value.delete(key);
},
clear() {
return value.clear();
},
has(key: string) {
return value.has(key);
},
};
}
// QuickLRU v5 and other caches work as-is
return value;
};
const defaultInternals: Options['_internals'] = {
request: undefined,
agent: {
http: undefined,
https: undefined,
http2: undefined,
},
h2session: undefined,
decompress: true,
timeout: {
connect: undefined,
lookup: undefined,
read: undefined,
request: undefined,
response: undefined,
secureConnect: undefined,
send: undefined,
socket: undefined,
},