got 12.0.0-beta.1 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,16 @@
1
1
  /// <reference types="node" />
2
- import { URL, URLSearchParams } from 'url';
3
- import { request as httpsRequest } from 'https';
4
- import type { Readable } from 'stream';
5
- import type { Socket } from 'net';
6
- import type { SecureContextOptions, DetailedPeerCertificate } from 'tls';
7
- import type { Agent as HttpAgent, ClientRequest } from 'http';
8
- import type { RequestOptions as HttpsRequestOptions, Agent as HttpsAgent } from 'https';
2
+ import { Buffer } from 'node:buffer';
3
+ import { URL, URLSearchParams } from 'node:url';
4
+ import { checkServerIdentity } from 'node:tls';
5
+ import { request as httpsRequest } from 'node:https';
6
+ import type { Readable } from 'node:stream';
7
+ import type { Socket } from 'node:net';
8
+ import type { SecureContextOptions, DetailedPeerCertificate } from 'node:tls';
9
+ import type { Agent as HttpAgent, ClientRequest } from 'node:http';
10
+ import type { RequestOptions as HttpsRequestOptions, Agent as HttpsAgent } from 'node:https';
9
11
  import CacheableLookup from 'cacheable-lookup';
10
12
  import http2wrapper, { ClientHttp2Session } from 'http2-wrapper';
13
+ import type { FormDataLike } from 'form-data-encoder';
11
14
  import type CacheableRequest from 'cacheable-request';
12
15
  import type ResponseLike from 'responselike';
13
16
  import type { IncomingMessageWithTimings } from '@szmarczak/http-timer';
@@ -49,39 +52,146 @@ All available hooks of Got.
49
52
  */
50
53
  export interface Hooks {
51
54
  /**
52
- Called with plain request options, right before their normalization.
55
+ Called with the plain request options, right before their normalization.
56
+
57
+ The second argument represents the current `Options` instance.
58
+
59
+ @default []
60
+
61
+ **Note:**
62
+ > - This hook must be synchronous.
63
+
64
+ **Note:**
65
+ > - This is called every time options are merged.
66
+
67
+ **Note:**
68
+ > - The `options` object may not have the `url` property. To modify it, use a `beforeRequest` hook instead.
69
+
70
+ **Note:**
71
+ > - This hook is called when a new instance of `Options` is created.
72
+ > - Do not confuse this with the creation of `Request` or `got(…)`.
73
+
74
+ **Note:**
75
+ > - When using `got(url)` or `got(url, undefined, defaults)` this hook will **not** be called.
76
+
53
77
  This is especially useful in conjunction with `got.extend()` when the input needs custom handling.
54
78
 
55
- __Note #1__: This hook must be synchronous!
79
+ For example, this can be used to fix typos to migrate from older versions faster.
56
80
 
57
- __Note #2__: Errors in this hook will be converted into an instances of `RequestError`.
81
+ @example
82
+ ```
83
+ import got from 'got';
58
84
 
59
- __Note #3__: The options object may not have a `url` property.
60
- To modify it, use a `beforeRequest` hook instead.
85
+ const instance = got.extend({
86
+ hooks: {
87
+ init: [
88
+ plain => {
89
+ if ('followRedirects' in plain) {
90
+ plain.followRedirect = plain.followRedirects;
91
+ delete plain.followRedirects;
92
+ }
93
+ }
94
+ ]
95
+ }
96
+ });
61
97
 
62
- @default []
98
+ // Normally, the following would throw:
99
+ const response = await instance(
100
+ 'https://example.com',
101
+ {
102
+ followRedirects: true
103
+ }
104
+ );
105
+
106
+ // There is no option named `followRedirects`, but we correct it in an `init` hook.
107
+ ```
108
+
109
+ Or you can create your own option and store it in a context:
110
+
111
+ ```
112
+ import got from 'got';
113
+
114
+ const instance = got.extend({
115
+ hooks: {
116
+ init: [
117
+ (plain, options) => {
118
+ if ('secret' in plain) {
119
+ options.context.secret = plain.secret;
120
+ delete plain.secret;
121
+ }
122
+ }
123
+ ],
124
+ beforeRequest: [
125
+ options => {
126
+ options.headers.secret = options.context.secret;
127
+ }
128
+ ]
129
+ }
130
+ });
131
+
132
+ const {headers} = await instance(
133
+ 'https://httpbin.org/anything',
134
+ {
135
+ secret: 'passphrase'
136
+ }
137
+ ).json();
138
+
139
+ console.log(headers.Secret);
140
+ //=> 'passphrase'
141
+ ```
63
142
  */
64
143
  init: InitHook[];
65
144
  /**
66
- Called with normalized request options.
67
- Got will make no further changes to the request before it is sent.
68
- This is especially useful in conjunction with `got.extend()` when you want to create an API client that, for example, uses HMAC-signing.
145
+ Called right before making the request with `options.createNativeRequestOptions()`.
146
+
147
+ This hook is especially useful in conjunction with `got.extend()` when you want to sign your request.
69
148
 
70
149
  @default []
150
+
151
+ **Note:**
152
+ > - Got will make no further changes to the request before it is sent.
153
+
154
+ **Note:**
155
+ > - 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.
156
+
157
+ @example
158
+ ```
159
+ import got from 'got';
160
+
161
+ const response = await got.post(
162
+ 'https://httpbin.org/anything',
163
+ {
164
+ json: {payload: 'old'},
165
+ hooks: {
166
+ beforeRequest: [
167
+ options => {
168
+ options.body = JSON.stringify({payload: 'new'});
169
+ options.headers['content-length'] = options.body.length.toString();
170
+ }
171
+ ]
172
+ }
173
+ }
174
+ );
175
+ ```
176
+
177
+ **Tip:**
178
+ > - 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.
179
+ > - [Read more about this tip](https://github.com/sindresorhus/got/blob/main/documentation/cache.md#advanced-caching-mechanisms).
71
180
  */
72
181
  beforeRequest: BeforeRequestHook[];
73
182
  /**
74
- Called with normalized request options and the redirect response.
75
- Got will make no further changes to the request.
76
- This is especially useful when you want to avoid dead sites.
183
+ The equivalent of `beforeRequest` but when redirecting.
77
184
 
78
185
  @default []
79
186
 
187
+ **Tip:**
188
+ > - This is especially useful when you want to avoid dead sites.
189
+
80
190
  @example
81
191
  ```
82
192
  import got from 'got';
83
193
 
84
- await got('https://example.com', {
194
+ const response = await got('https://example.com', {
85
195
  hooks: {
86
196
  beforeRedirect: [
87
197
  (options, response) => {
@@ -96,19 +206,17 @@ export interface Hooks {
96
206
  */
97
207
  beforeRedirect: BeforeRedirectHook[];
98
208
  /**
99
- Called with an `Error` instance.
100
- The error is passed to the hook right before it's thrown.
101
- This is especially useful when you want to have more detailed errors.
209
+ Called with a `RequestError` instance. The error is passed to the hook right before it's thrown.
102
210
 
103
- __Note__: Errors thrown while normalizing input options are thrown directly and not part of this hook.
211
+ This is especially useful when you want to have more detailed errors.
104
212
 
105
213
  @default []
106
214
 
107
- @example
108
215
  ```
109
216
  import got from 'got';
110
217
 
111
- await got('https://api.github.com/some-endpoint', {
218
+ await got('https://api.github.com/repos/sindresorhus/got/commits', {
219
+ responseType: 'json',
112
220
  hooks: {
113
221
  beforeError: [
114
222
  error => {
@@ -127,26 +235,31 @@ export interface Hooks {
127
235
  */
128
236
  beforeError: BeforeErrorHook[];
129
237
  /**
130
- Called with normalized request options, the error and the retry count.
131
- Got will make no further changes to the request.
132
- This is especially useful when some extra work is required before the next try.
133
-
134
- __Note__: When using streams, this hook is ignored.
135
- __Note__: When retrying in a `afterResponse` hook, all remaining `beforeRetry` hooks will be called without the `error` and `retryCount` arguments.
238
+ The equivalent of `beforeError` but when retrying. Additionally, there is a second argument `retryCount`, the current retry number.
136
239
 
137
240
  @default []
138
241
 
242
+ **Note:**
243
+ > - When using the Stream API, this hook is ignored.
244
+
245
+ **Note:**
246
+ > - When retrying, the `beforeRequest` hook is called afterwards.
247
+
248
+ **Note:**
249
+ > - If no retry occurs, the `beforeError` hook is called instead.
250
+
251
+ This hook is especially useful when you want to retrieve the cause of a retry.
252
+
139
253
  @example
140
254
  ```
141
255
  import got from 'got';
142
256
 
143
- got.post('https://example.com', {
257
+ await got('https://httpbin.org/status/500', {
144
258
  hooks: {
145
259
  beforeRetry: [
146
- (options, error, retryCount) => {
147
- if (error.response.statusCode === 413) { // Payload too large
148
- options.body = getNewBody();
149
- }
260
+ (error, retryCount) => {
261
+ console.log(`Retrying [${retryCount}]: ${error.code}`);
262
+ // Retrying [1]: ERR_NON_2XX_3XX_RESPONSE
150
263
  }
151
264
  ]
152
265
  }
@@ -155,13 +268,16 @@ export interface Hooks {
155
268
  */
156
269
  beforeRetry: BeforeRetryHook[];
157
270
  /**
158
- Called with [response object](#response) and a retry function.
159
- Calling the retry function will trigger `beforeRetry` hooks.
271
+ Each function should return the response. This is especially useful when you want to refresh an access token.
160
272
 
161
- Each function should return the response.
162
- This is especially useful when you want to refresh an access token.
273
+ @default []
163
274
 
164
- __Note__: When using streams, this hook is ignored.
275
+ **Note:**
276
+ > - When using the Stream API, this hook is ignored.
277
+
278
+ **Note:**
279
+ > - Calling the `retryWithMergedOptions` function will trigger `beforeRetry` hooks. If the retry is successful, all remaining `afterResponse` hooks will be called. In case of an error, `beforeRetry` hooks will be called instead.
280
+ Meanwhile the `init`, `beforeRequest` , `beforeRedirect` as well as already executed `afterResponse` hooks will be skipped.
165
281
 
166
282
  @example
167
283
  ```
@@ -171,15 +287,17 @@ export interface Hooks {
171
287
  hooks: {
172
288
  afterResponse: [
173
289
  (response, retryWithMergedOptions) => {
174
- if (response.statusCode === 401) { // Unauthorized
290
+ // Unauthorized
291
+ if (response.statusCode === 401) {
292
+ // Refresh the access token
175
293
  const updatedOptions = {
176
294
  headers: {
177
- token: getNewToken() // Refresh the access token
295
+ token: getNewToken()
178
296
  }
179
297
  };
180
298
 
181
- // Save for further requests
182
- instance.defaults.options = got.mergeOptions(instance.defaults.options, updatedOptions);
299
+ // Update the defaults
300
+ instance.defaults.options.merge(updatedOptions);
183
301
 
184
302
  // Make a new retry
185
303
  return retryWithMergedOptions(updatedOptions);
@@ -190,7 +308,7 @@ export interface Hooks {
190
308
  }
191
309
  ],
192
310
  beforeRetry: [
193
- (options, error, retryCount) => {
311
+ error => {
194
312
  // This will be called on `retryWithMergedOptions(...)`
195
313
  }
196
314
  ]
@@ -247,8 +365,8 @@ export interface RetryOptions {
247
365
  noise: number;
248
366
  maxRetryAfter?: number;
249
367
  }
250
- export declare type CreateConnectionFunction = (options: NativeRequestOptions, oncreate: (error: Error, socket: Socket) => void) => Socket;
251
- export declare type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => Error | void;
368
+ export declare type CreateConnectionFunction = (options: NativeRequestOptions, oncreate: (error: NodeJS.ErrnoException, socket: Socket) => void) => Socket;
369
+ export declare type CheckServerIdentityFunction = (hostname: string, certificate: DetailedPeerCertificate) => NodeJS.ErrnoException | void;
252
370
  export interface CacheOptions {
253
371
  shared?: boolean;
254
372
  cacheHeuristic?: number;
@@ -354,13 +472,13 @@ export interface PaginationOptions<ElementType, BodyType> {
354
472
  const limit = 10;
355
473
 
356
474
  const items = got.paginate('https://example.com/items', {
357
- searchParameters: {
475
+ searchParams: {
358
476
  limit,
359
477
  offset: 0
360
478
  },
361
479
  pagination: {
362
480
  paginate: ({response, currentItems}) => {
363
- const previousSearchParams = response.request.options.searchParameters;
481
+ const previousSearchParams = response.request.options.searchParams;
364
482
  const previousOffset = previousSearchParams.get('offset');
365
483
 
366
484
  if (currentItems.length < limit) {
@@ -368,7 +486,7 @@ export interface PaginationOptions<ElementType, BodyType> {
368
486
  }
369
487
 
370
488
  return {
371
- searchParameters: {
489
+ searchParams: {
372
490
  ...previousSearchParams,
373
491
  offset: Number(previousOffset) + limit,
374
492
  }
@@ -443,7 +561,7 @@ export default class Options {
443
561
  private _internals;
444
562
  private _merging;
445
563
  private readonly _init;
446
- constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options | OptionsInit);
564
+ constructor(input?: string | URL | OptionsInit, options?: OptionsInit, defaults?: Options);
447
565
  merge(options?: OptionsInit | Options): void;
448
566
  /**
449
567
  Custom request function.
@@ -558,12 +676,12 @@ export default class Options {
558
676
 
559
677
  __Note #4__: This option is not enumerable and will not be merged with the instance defaults.
560
678
 
561
- The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
679
+ The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData) / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
562
680
 
563
681
  Since Got 12, the `content-length` is not automatically set when `body` is a `fs.createReadStream`.
564
682
  */
565
- get body(): string | Buffer | Readable | Generator | AsyncGenerator | undefined;
566
- set body(value: string | Buffer | Readable | Generator | AsyncGenerator | undefined);
683
+ get body(): string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined;
684
+ set body(value: string | Buffer | Readable | Generator | AsyncGenerator | FormDataLike | undefined);
567
685
  /**
568
686
  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).
569
687
 
@@ -596,10 +714,10 @@ export default class Options {
596
714
  @example
597
715
  ```
598
716
  await got('https://example.com/?query=a b'); //=> https://example.com/?query=a%20b
599
- await got('https://example.com/', {searchParameters: {query: 'a b'}}); //=> https://example.com/?query=a+b
717
+ await got('https://example.com/', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
600
718
 
601
- // The query string is overridden by `searchParameters`
602
- await got('https://example.com/?query=a b', {searchParameters: {query: 'a b'}}); //=> https://example.com/?query=a+b
719
+ // The query string is overridden by `searchParams`
720
+ await got('https://example.com/?query=a b', {searchParams: {query: 'a b'}}); //=> https://example.com/?query=a+b
603
721
  ```
604
722
  */
605
723
  get url(): string | URL | undefined;
@@ -629,11 +747,11 @@ export default class Options {
629
747
  ```
630
748
  import got from 'got';
631
749
 
632
- const searchParameters = new URLSearchParams([['key', 'a'], ['key', 'b']]);
750
+ const searchParams = new URLSearchParams([['key', 'a'], ['key', 'b']]);
633
751
 
634
- await got('https://example.com', {searchParameters});
752
+ await got('https://example.com', {searchParams});
635
753
 
636
- console.log(searchParameters.toString());
754
+ console.log(searchParams.toString());
637
755
  //=> 'key=a&key=b'
638
756
  ```
639
757
  */
@@ -981,25 +1099,27 @@ export default class Options {
981
1099
  headers: Headers;
982
1100
  timeout: Delays;
983
1101
  request: RequestFunction | undefined;
1102
+ username: string;
1103
+ password: string;
984
1104
  json: Record<string, any> | undefined;
985
1105
  retry: Partial<RetryOptions>;
986
1106
  agent: Agents;
987
1107
  h2session: http2wrapper.ClientHttp2Session | undefined;
988
1108
  decompress: boolean;
989
1109
  prefixUrl: string | URL;
990
- body: string | Readable | Buffer | Generator<unknown, any, unknown> | AsyncGenerator<unknown, any, unknown> | undefined;
1110
+ body: string | Readable | Buffer | Generator<unknown, any, unknown> | AsyncGenerator<unknown, any, unknown> | FormDataLike | undefined;
991
1111
  form: Record<string, any> | undefined;
992
1112
  url: string | URL | undefined;
993
1113
  cookieJar: PromiseCookieJar | ToughCookieJar | undefined;
994
1114
  ignoreInvalidCookies: boolean;
995
1115
  searchParams: string | SearchParameters | URLSearchParams | undefined;
996
1116
  dnsLookup: {
997
- (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
998
- (hostname: string, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1117
+ (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1118
+ (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
999
1119
  (hostname: string, options: import("cacheable-lookup").LookupOptions & {
1000
1120
  all: true;
1001
- }, callback: (error: NodeJS.ErrnoException, result: readonly import("cacheable-lookup").EntryObject[]) => void): void;
1002
- (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1121
+ }, callback: (error: NodeJS.ErrnoException | null, result: readonly import("cacheable-lookup").EntryObject[]) => void): void;
1122
+ (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1003
1123
  } | undefined;
1004
1124
  dnsCache: boolean | CacheableLookup | undefined;
1005
1125
  context: Record<string, unknown>;
@@ -1008,8 +1128,6 @@ export default class Options {
1008
1128
  maxRedirects: number;
1009
1129
  cache: string | boolean | CacheableRequest.StorageAdapter | undefined;
1010
1130
  throwHttpErrors: boolean;
1011
- username: string;
1012
- password: string;
1013
1131
  http2: boolean;
1014
1132
  allowGetBody: boolean;
1015
1133
  methodRewriting: boolean;
@@ -1030,13 +1148,14 @@ export default class Options {
1030
1148
  maxHeaderSize: number | undefined;
1031
1149
  };
1032
1150
  createNativeRequestOptions(): {
1151
+ ALPNProtocols: string[] | undefined;
1033
1152
  ca: string | Buffer | (string | Buffer)[] | undefined;
1034
1153
  cert: string | Buffer | (string | Buffer)[] | undefined;
1035
1154
  key: string | Buffer | (Buffer | import("tls").KeyObject)[] | undefined;
1036
1155
  passphrase: string | undefined;
1037
1156
  pfx: PfxType;
1038
1157
  rejectUnauthorized: boolean | undefined;
1039
- checkServerIdentity: CheckServerIdentityFunction;
1158
+ checkServerIdentity: CheckServerIdentityFunction | typeof checkServerIdentity;
1040
1159
  ciphers: string | undefined;
1041
1160
  honorCipherOrder: boolean | undefined;
1042
1161
  minVersion: import("tls").SecureVersion | undefined;
@@ -1047,12 +1166,12 @@ export default class Options {
1047
1166
  ecdhCurve: string | undefined;
1048
1167
  crl: string | Buffer | (string | Buffer)[] | undefined;
1049
1168
  lookup: {
1050
- (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1051
- (hostname: string, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1169
+ (hostname: string, family: import("cacheable-lookup").IPFamily, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1170
+ (hostname: string, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1052
1171
  (hostname: string, options: import("cacheable-lookup").LookupOptions & {
1053
1172
  all: true;
1054
- }, callback: (error: NodeJS.ErrnoException, result: readonly import("cacheable-lookup").EntryObject[]) => void): void;
1055
- (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1173
+ }, callback: (error: NodeJS.ErrnoException | null, result: readonly import("cacheable-lookup").EntryObject[]) => void): void;
1174
+ (hostname: string, options: import("cacheable-lookup").LookupOptions, callback: (error: NodeJS.ErrnoException | null, address: string, family: import("cacheable-lookup").IPFamily) => void): void;
1056
1175
  } | undefined;
1057
1176
  family: DnsLookupIpVersion;
1058
1177
  agent: false | Agents | HttpAgent | undefined;
@@ -1064,6 +1183,7 @@ export default class Options {
1064
1183
  createConnection: CreateConnectionFunction | undefined;
1065
1184
  timeout: number | undefined;
1066
1185
  h2session: http2wrapper.ClientHttp2Session | undefined;
1186
+ signal?: AbortSignal | undefined;
1067
1187
  protocol?: string | null | undefined;
1068
1188
  host?: string | null | undefined;
1069
1189
  hostname?: string | null | undefined;
@@ -1086,8 +1206,8 @@ export default class Options {
1086
1206
  immutableMinTimeToLive?: number | undefined;
1087
1207
  ignoreCargoCult?: boolean | undefined;
1088
1208
  };
1089
- getRequestFunction(): RequestFunction | typeof httpsRequest;
1090
- getFallbackRequestFunction(): RequestFunction | typeof httpsRequest;
1209
+ getRequestFunction(): RequestFunction | typeof httpsRequest | undefined;
1210
+ getFallbackRequestFunction(): RequestFunction | typeof httpsRequest | undefined;
1091
1211
  freeze(): void;
1092
1212
  }
1093
1213
  export {};