/
normalize-arguments.ts
425 lines (353 loc) 路 12.7 KB
/
normalize-arguments.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
import {promisify} from 'util';
import http = require('http');
import https = require('https');
import CacheableLookup from 'cacheable-lookup';
import CacheableRequest = require('cacheable-request');
import is from '@sindresorhus/is';
import lowercaseKeys = require('lowercase-keys');
import toReadableStream = require('to-readable-stream');
import Keyv = require('keyv');
import optionsToUrl from './utils/options-to-url';
import {UnsupportedProtocolError} from './errors';
import merge from './utils/merge';
import knownHookEvents from './known-hook-events';
import {
Options,
NormalizedOptions,
Method,
URLOrOptions,
Defaults
} from './utils/types';
import dynamicRequire from './utils/dynamic-require';
import getBodySize from './utils/get-body-size';
import isFormData from './utils/is-form-data';
import supportsBrotli from './utils/supports-brotli';
// `preNormalizeArguments` normalizes these options: `headers`, `prefixUrl`, `hooks`, `timeout`, `retry` and `method`.
// `normalizeArguments` is *only* called on `got(...)`. It normalizes the URL and performs `mergeOptions(...)`.
// `normalizeRequestArguments` converts Got options into HTTP options.
type NonEnumerableProperty = 'context' | 'body' | 'json' | 'form';
const nonEnumerableProperties: NonEnumerableProperty[] = [
'context',
'body',
'json',
'form'
];
export const preNormalizeArguments = (options: Options, defaults?: NormalizedOptions): NormalizedOptions => {
// `options.headers`
if (is.undefined(options.headers)) {
options.headers = {};
} else {
options.headers = lowercaseKeys(options.headers);
}
// `options.prefixUrl`
if (is.urlInstance(options.prefixUrl) || is.string(options.prefixUrl)) {
options.prefixUrl = options.prefixUrl.toString();
if (options.prefixUrl.length !== 0 && !options.prefixUrl.endsWith('/')) {
options.prefixUrl += '/';
}
} else {
options.prefixUrl = defaults ? defaults.prefixUrl : '';
}
// `options.hooks`
if (is.undefined(options.hooks)) {
options.hooks = {};
}
if (is.object(options.hooks)) {
for (const event of knownHookEvents) {
if (Reflect.has(options.hooks, event)) {
if (!is.array(options.hooks[event])) {
throw new TypeError(`Parameter \`${event}\` must be an Array, not ${is(options.hooks[event])}`);
}
} else {
options.hooks[event] = [];
}
}
} else {
throw new TypeError(`Parameter \`hooks\` must be an Object, not ${is(options.hooks)}`);
}
if (defaults) {
for (const event of knownHookEvents) {
// @ts-ignore TS is dumb.
options.hooks[event] = [
...defaults.hooks[event],
...options.hooks[event]
];
}
}
// `options.timeout`
if (is.number(options.timeout)) {
options.timeout = {request: options.timeout};
} else if (!is.object(options.timeout)) {
options.timeout = {};
}
// `options.retry`
const {retry} = options;
if (defaults) {
options.retry = {...defaults.retry};
} else {
options.retry = {
calculateDelay: retryObject => retryObject.computedValue,
limit: 0,
methods: [],
statusCodes: [],
errorCodes: [],
maxRetryAfter: undefined
};
}
if (is.object(retry)) {
options.retry = {
...options.retry,
...retry
};
} else if (is.number(retry)) {
options.retry.limit = retry;
}
if (options.retry.maxRetryAfter === undefined) {
options.retry.maxRetryAfter = Math.min(
...[options.timeout.request, options.timeout.connect].filter(n => !is.nullOrUndefined(n))
);
}
options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase()))] as Method[];
options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
// `options.dnsCache`
if (options.dnsCache && !(options.dnsCache instanceof CacheableLookup)) {
options.dnsCache = new CacheableLookup({cacheAdapter: options.dnsCache as Keyv});
}
// `options.method`
if (is.string(options.method)) {
options.method = options.method.toUpperCase() as Method;
} else {
options.method = defaults?.method || 'GET';
}
// Better memory management, so we don't have to generate a new object every time
if (options.cache) {
(options as NormalizedOptions).cacheableRequest = new CacheableRequest(
(options, handler) => options.request(options, handler),
options.cache as any
);
}
// `options.cookieJar`
if (is.object(options.cookieJar)) {
let {setCookie, getCookieString} = options.cookieJar;
// Horrible `tough-cookie` check
if (setCookie.length === 4 && getCookieString.length === 0) {
if (!Reflect.has(setCookie, promisify.custom)) {
setCookie = promisify(setCookie.bind(options.cookieJar));
getCookieString = promisify(getCookieString.bind(options.cookieJar));
}
} else if (setCookie.length !== 2) {
throw new TypeError('`options.cookieJar.setCookie` needs to be an async function with 2 arguments');
} else if (getCookieString.length !== 1) {
throw new TypeError('`options.cookieJar.getCookieString` needs to be an async function with 1 argument');
}
options.cookieJar = {setCookie, getCookieString};
}
return options as NormalizedOptions;
};
export const mergeOptions = (...sources: Options[]): NormalizedOptions => {
const mergedOptions = preNormalizeArguments({});
// Non enumerable properties shall not be merged
const properties = {};
for (const source of sources) {
if (!source) {
continue;
}
merge(mergedOptions, preNormalizeArguments(merge({}, source), mergedOptions));
for (const name of nonEnumerableProperties) {
if (!Reflect.has(source, name)) {
continue;
}
properties[name] = {
writable: true,
configurable: true,
enumerable: false,
value: source[name]
};
}
}
Object.defineProperties(mergedOptions, properties);
return mergedOptions;
};
export const normalizeArguments = (url: URLOrOptions, options?: Options, defaults?: Defaults): NormalizedOptions => {
// Merge options
if (typeof url === 'undefined') {
throw new TypeError('Missing `url` argument');
}
if (typeof options === 'undefined') {
options = {};
}
if (is.urlInstance(url) || is.string(url)) {
options.url = url;
options = mergeOptions(defaults && defaults.options, options);
} else {
if (Reflect.has(url, 'resolve')) {
throw new Error('The legacy `url.Url` is deprecated. Use `URL` instead.');
}
options = mergeOptions(defaults && defaults.options, url, options);
}
// Normalize URL
// TODO: drop `optionsToUrl` in Got 12
if (is.string(options.url)) {
options.url = (options.prefixUrl as string) + options.url;
options.url = options.url.replace(/^unix:/, 'http://$&');
if (options.searchParams || options.search) {
options.url = options.url.split('?')[0];
}
options.url = optionsToUrl({
origin: options.url,
...options
});
} else if (!is.urlInstance(options.url)) {
options.url = optionsToUrl({origin: options.prefixUrl as string, ...options});
}
const normalizedOptions = options as NormalizedOptions;
// Make it possible to change `options.prefixUrl`
let prefixUrl = options.prefixUrl as string;
Object.defineProperty(options, 'prefixUrl', {
set: (value: string) => {
if (!normalizedOptions.url.href.startsWith(value)) {
throw new Error(`Cannot change \`prefixUrl\` from ${prefixUrl} to ${value}: ${normalizedOptions.url.href}`);
}
normalizedOptions.url = new URL(value + normalizedOptions.url.href.slice(prefixUrl.length));
prefixUrl = value;
},
get: () => prefixUrl
});
// Make it possible to remove default headers
for (const [key, value] of Object.entries(options.headers)) {
if (is.undefined(value)) {
delete options.headers[key];
} else if (is.null_(value)) {
throw new TypeError('Use `undefined` instead of `null` to delete HTTP headers');
}
}
for (const hook of options.hooks.init) {
if (is.asyncFunction(hook)) {
throw new TypeError('The `init` hook must be a synchronous function');
}
// @ts-ignore TS is dumb.
hook(normalizedOptions);
}
return normalizedOptions;
};
const withoutBody: ReadonlySet<string> = new Set(['GET', 'HEAD']);
export type NormalizedRequestArguments = https.RequestOptions & {
body?: ReadableStream;
url: Pick<NormalizedOptions, 'url'>;
};
export const normalizeRequestArguments = async (options: NormalizedOptions): Promise<NormalizedRequestArguments> => {
options = mergeOptions(options);
// Serialize body
const {headers} = options;
const isForm = !is.undefined(options.form);
const isJSON = !is.undefined(options.json);
const isBody = !is.undefined(options.body);
if ((isBody || isForm || isJSON) && withoutBody.has(options.method)) {
throw new TypeError(`The \`${options.method}\` method cannot be used with a body`);
}
if ([isBody, isForm, isJSON].filter(isTrue => isTrue).length > 1) {
throw new TypeError('The `body`, `json` and `form` options are mutually exclusive');
}
if (isBody) {
if (is.object(options.body) && isFormData(options.body)) {
// Special case for https://github.com/form-data/form-data
if (!Reflect.has(headers, 'content-type')) {
headers['content-type'] = `multipart/form-data; boundary=${options.body.getBoundary()}`;
}
} else if (!is.nodeStream(options.body) && !is.string(options.body) && !is.buffer(options.body)) {
throw new TypeError('The `body` option must be a stream.Readable, string or Buffer');
}
} else if (isForm) {
if (!is.object(options.form)) {
throw new TypeError('The `form` option must be an Object');
}
if (!Reflect.has(headers, 'content-type')) {
headers['content-type'] = 'application/x-www-form-urlencoded';
}
options.body = (new URLSearchParams(options.form as Record<string, string>)).toString();
} else if (isJSON) {
if (!Reflect.has(headers, 'content-type')) {
headers['content-type'] = 'application/json';
}
options.body = JSON.stringify(options.json);
}
const uploadBodySize = await getBodySize(options);
if (!is.nodeStream(options.body)) {
options.body = toReadableStream(options.body);
}
// See https://tools.ietf.org/html/rfc7230#section-3.3.2
// A user agent SHOULD send a Content-Length in a request message when
// no Transfer-Encoding is sent and the request method defines a meaning
// for an enclosed payload body. For example, a Content-Length header
// field is normally sent in a POST request even when the value is 0
// (indicating an empty payload body). A user agent SHOULD NOT send a
// Content-Length header field when the request message does not contain
// a payload body and the method semantics do not anticipate such a
// body.
if (!Reflect.has(headers, 'content-length') && !Reflect.has(headers, 'transfer-encoding')) {
if (
(options.method === 'POST' || options.method === 'PUT' || options.method === 'PATCH') &&
!is.undefined(uploadBodySize)
) {
headers['content-length'] = String(uploadBodySize);
}
}
if (!options.isStream && options.responseType === 'json' && is.undefined(headers.accept)) {
headers.accept = 'application/json';
}
if (options.decompress && is.undefined(headers['accept-encoding'])) {
headers['accept-encoding'] = supportsBrotli ? 'gzip, deflate, br' : 'gzip, deflate';
}
// Validate URL
if (options.url.protocol !== 'http:' && options.url.protocol !== 'https:') {
throw new UnsupportedProtocolError(options);
}
decodeURI(options.url.toString());
// Normalize request function
if (!is.function_(options.request)) {
options.request = options.url.protocol === 'https:' ? https.request : http.request;
}
// UNIX sockets
if (options.url.hostname === 'unix') {
const matches = /(?<socketPath>.+?):(?<path>.+)/.exec(options.url.pathname);
if (matches?.groups) {
const {socketPath, path} = matches.groups;
// It's a bug!
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
options = {
...options,
socketPath,
path,
host: ''
} as NormalizedOptions;
}
}
if (is.object(options.agent)) {
options.agent = options.agent[options.url.protocol.slice(0, -1)] || options.agent;
}
if (options.dnsCache) {
options.lookup = options.dnsCache.lookup;
}
/* istanbul ignore next: electron.net is broken */
// No point in typing process.versions correctly, as
// `process.version.electron` is used only once, right here.
if (options.useElectronNet && (process.versions as any).electron) {
const electron = dynamicRequire(module, 'electron') as any; // Trick webpack
options.request = electron.net.request ?? electron.remote.net.request;
}
// Got's `timeout` is an object, http's `timeout` is a number, so they're not compatible.
delete options.timeout;
// Set cookies
if (options.cookieJar) {
const cookieString = await options.cookieJar.getCookieString(options.url.toString());
if (is.nonEmptyString(cookieString)) {
options.headers.cookie = cookieString;
} else {
delete options.headers.cookie;
}
}
// `http-cache-semantics` checks this
delete options.url;
return options as unknown as NormalizedRequestArguments;
};