blob: 4c5090a5c5159c9eb953c47bf9a2b7e1201724b6 [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2const EventEmitter = require('events');
3const http = require('http');
4const https = require('https');
5const PassThrough = require('stream').PassThrough;
6const urlLib = require('url');
7const querystring = require('querystring');
8const duplexer3 = require('duplexer3');
9const isStream = require('is-stream');
10const getStream = require('get-stream');
11const timedOut = require('timed-out');
12const urlParseLax = require('url-parse-lax');
13const urlToOptions = require('url-to-options');
14const lowercaseKeys = require('lowercase-keys');
15const decompressResponse = require('decompress-response');
16const isRetryAllowed = require('is-retry-allowed');
17const Buffer = require('safe-buffer').Buffer;
18const isURL = require('isurl');
19const isPlainObj = require('is-plain-obj');
20const PCancelable = require('p-cancelable');
21const pTimeout = require('p-timeout');
22const pkg = require('./package');
23
24const getMethodRedirectCodes = new Set([300, 301, 302, 303, 304, 305, 307, 308]);
25const allMethodRedirectCodes = new Set([300, 303, 307, 308]);
26
27function requestAsEventEmitter(opts) {
28 opts = opts || {};
29
30 const ee = new EventEmitter();
31 const requestUrl = opts.href || urlLib.resolve(urlLib.format(opts), opts.path);
32 const redirects = [];
33 let retryCount = 0;
34 let redirectUrl;
35
36 const get = opts => {
37 if (opts.protocol !== 'http:' && opts.protocol !== 'https:') {
38 ee.emit('error', new got.UnsupportedProtocolError(opts));
39 return;
40 }
41
42 let fn = opts.protocol === 'https:' ? https : http;
43
44 if (opts.useElectronNet && process.versions.electron) {
45 const electron = require('electron');
46 fn = electron.net || electron.remote.net;
47 }
48
49 const req = fn.request(opts, res => {
50 const statusCode = res.statusCode;
51
52 res.url = redirectUrl || requestUrl;
53 res.requestUrl = requestUrl;
54
55 const followRedirect = opts.followRedirect && 'location' in res.headers;
56 const redirectGet = followRedirect && getMethodRedirectCodes.has(statusCode);
57 const redirectAll = followRedirect && allMethodRedirectCodes.has(statusCode);
58
59 if (redirectAll || (redirectGet && (opts.method === 'GET' || opts.method === 'HEAD'))) {
60 res.resume();
61
62 if (statusCode === 303) {
63 // Server responded with "see other", indicating that the resource exists at another location,
64 // and the client should request it from that location via GET or HEAD.
65 opts.method = 'GET';
66 }
67
68 if (redirects.length >= 10) {
69 ee.emit('error', new got.MaxRedirectsError(statusCode, redirects, opts), null, res);
70 return;
71 }
72
73 const bufferString = Buffer.from(res.headers.location, 'binary').toString();
74
75 redirectUrl = urlLib.resolve(urlLib.format(opts), bufferString);
76
77 redirects.push(redirectUrl);
78
79 const redirectOpts = Object.assign({}, opts, urlLib.parse(redirectUrl));
80
81 ee.emit('redirect', res, redirectOpts);
82
83 get(redirectOpts);
84
85 return;
86 }
87
88 setImmediate(() => {
89 const response = opts.decompress === true &&
90 typeof decompressResponse === 'function' &&
91 req.method !== 'HEAD' ? decompressResponse(res) : res;
92
93 if (!opts.decompress && ['gzip', 'deflate'].indexOf(res.headers['content-encoding']) !== -1) {
94 opts.encoding = null;
95 }
96
97 response.redirectUrls = redirects;
98
99 ee.emit('response', response);
100 });
101 });
102
103 req.once('error', err => {
104 const backoff = opts.retries(++retryCount, err);
105
106 if (backoff) {
107 setTimeout(get, backoff, opts);
108 return;
109 }
110
111 ee.emit('error', new got.RequestError(err, opts));
112 });
113
114 if (opts.gotTimeout) {
115 timedOut(req, opts.gotTimeout);
116 }
117
118 setImmediate(() => {
119 ee.emit('request', req);
120 });
121 };
122
123 setImmediate(() => {
124 get(opts);
125 });
126 return ee;
127}
128
129function asPromise(opts) {
130 const timeoutFn = requestPromise => opts.gotTimeout && opts.gotTimeout.request ?
131 pTimeout(requestPromise, opts.gotTimeout.request, new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts)) :
132 requestPromise;
133
134 return timeoutFn(new PCancelable((onCancel, resolve, reject) => {
135 const ee = requestAsEventEmitter(opts);
136 let cancelOnRequest = false;
137
138 onCancel(() => {
139 cancelOnRequest = true;
140 });
141
142 ee.on('request', req => {
143 if (cancelOnRequest) {
144 req.abort();
145 }
146
147 onCancel(() => {
148 req.abort();
149 });
150
151 if (isStream(opts.body)) {
152 opts.body.pipe(req);
153 opts.body = undefined;
154 return;
155 }
156
157 req.end(opts.body);
158 });
159
160 ee.on('response', res => {
161 const stream = opts.encoding === null ? getStream.buffer(res) : getStream(res, opts);
162
163 stream
164 .catch(err => reject(new got.ReadError(err, opts)))
165 .then(data => {
166 const statusCode = res.statusCode;
167 const limitStatusCode = opts.followRedirect ? 299 : 399;
168
169 res.body = data;
170
171 if (opts.json && res.body) {
172 try {
173 res.body = JSON.parse(res.body);
174 } catch (e) {
175 if (statusCode >= 200 && statusCode < 300) {
176 throw new got.ParseError(e, statusCode, opts, data);
177 }
178 }
179 }
180
181 if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
182 throw new got.HTTPError(statusCode, res.headers, opts);
183 }
184
185 resolve(res);
186 })
187 .catch(err => {
188 Object.defineProperty(err, 'response', {value: res});
189 reject(err);
190 });
191 });
192
193 ee.on('error', reject);
194 }));
195}
196
197function asStream(opts) {
198 const input = new PassThrough();
199 const output = new PassThrough();
200 const proxy = duplexer3(input, output);
201 let timeout;
202
203 if (opts.gotTimeout && opts.gotTimeout.request) {
204 timeout = setTimeout(() => {
205 proxy.emit('error', new got.RequestError({message: 'Request timed out', code: 'ETIMEDOUT'}, opts));
206 }, opts.gotTimeout.request);
207 }
208
209 if (opts.json) {
210 throw new Error('got can not be used as stream when options.json is used');
211 }
212
213 if (opts.body) {
214 proxy.write = () => {
215 throw new Error('got\'s stream is not writable when options.body is used');
216 };
217 }
218
219 const ee = requestAsEventEmitter(opts);
220
221 ee.on('request', req => {
222 proxy.emit('request', req);
223
224 if (isStream(opts.body)) {
225 opts.body.pipe(req);
226 return;
227 }
228
229 if (opts.body) {
230 req.end(opts.body);
231 return;
232 }
233
234 if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
235 input.pipe(req);
236 return;
237 }
238
239 req.end();
240 });
241
242 ee.on('response', res => {
243 clearTimeout(timeout);
244
245 const statusCode = res.statusCode;
246
247 res.pipe(output);
248
249 if (statusCode !== 304 && (statusCode < 200 || statusCode > 299)) {
250 proxy.emit('error', new got.HTTPError(statusCode, res.headers, opts), null, res);
251 return;
252 }
253
254 proxy.emit('response', res);
255 });
256
257 ee.on('redirect', proxy.emit.bind(proxy, 'redirect'));
258 ee.on('error', proxy.emit.bind(proxy, 'error'));
259
260 return proxy;
261}
262
263function normalizeArguments(url, opts) {
264 if (typeof url !== 'string' && typeof url !== 'object') {
265 throw new TypeError(`Parameter \`url\` must be a string or object, not ${typeof url}`);
266 } else if (typeof url === 'string') {
267 url = url.replace(/^unix:/, 'http://$&');
268 url = urlParseLax(url);
269 } else if (isURL.lenient(url)) {
270 url = urlToOptions(url);
271 }
272
273 if (url.auth) {
274 throw new Error('Basic authentication must be done with auth option');
275 }
276
277 opts = Object.assign(
278 {
279 path: '',
280 retries: 2,
281 decompress: true,
282 useElectronNet: true
283 },
284 url,
285 {
286 protocol: url.protocol || 'http:' // Override both null/undefined with default protocol
287 },
288 opts
289 );
290
291 opts.headers = Object.assign({
292 'user-agent': `${pkg.name}/${pkg.version} (https://github.com/sindresorhus/got)`,
293 'accept-encoding': 'gzip,deflate'
294 }, lowercaseKeys(opts.headers));
295
296 const query = opts.query;
297
298 if (query) {
299 if (typeof query !== 'string') {
300 opts.query = querystring.stringify(query);
301 }
302
303 opts.path = `${opts.path.split('?')[0]}?${opts.query}`;
304 delete opts.query;
305 }
306
307 if (opts.json && opts.headers.accept === undefined) {
308 opts.headers.accept = 'application/json';
309 }
310
311 const body = opts.body;
312 if (body !== null && body !== undefined) {
313 const headers = opts.headers;
314 if (!isStream(body) && typeof body !== 'string' && !Buffer.isBuffer(body) && !(opts.form || opts.json)) {
315 throw new TypeError('options.body must be a ReadableStream, string, Buffer or plain Object');
316 }
317
318 const canBodyBeStringified = isPlainObj(body) || Array.isArray(body);
319 if ((opts.form || opts.json) && !canBodyBeStringified) {
320 throw new TypeError('options.body must be a plain Object or Array when options.form or options.json is used');
321 }
322
323 if (isStream(body) && typeof body.getBoundary === 'function') {
324 // Special case for https://github.com/form-data/form-data
325 headers['content-type'] = headers['content-type'] || `multipart/form-data; boundary=${body.getBoundary()}`;
326 } else if (opts.form && canBodyBeStringified) {
327 headers['content-type'] = headers['content-type'] || 'application/x-www-form-urlencoded';
328 opts.body = querystring.stringify(body);
329 } else if (opts.json && canBodyBeStringified) {
330 headers['content-type'] = headers['content-type'] || 'application/json';
331 opts.body = JSON.stringify(body);
332 }
333
334 if (headers['content-length'] === undefined && headers['transfer-encoding'] === undefined && !isStream(body)) {
335 const length = typeof opts.body === 'string' ? Buffer.byteLength(opts.body) : opts.body.length;
336 headers['content-length'] = length;
337 }
338
339 opts.method = (opts.method || 'POST').toUpperCase();
340 } else {
341 opts.method = (opts.method || 'GET').toUpperCase();
342 }
343
344 if (opts.hostname === 'unix') {
345 const matches = /(.+?):(.+)/.exec(opts.path);
346
347 if (matches) {
348 opts.socketPath = matches[1];
349 opts.path = matches[2];
350 opts.host = null;
351 }
352 }
353
354 if (typeof opts.retries !== 'function') {
355 const retries = opts.retries;
356
357 opts.retries = (iter, err) => {
358 if (iter > retries || !isRetryAllowed(err)) {
359 return 0;
360 }
361
362 const noise = Math.random() * 100;
363
364 return ((1 << iter) * 1000) + noise;
365 };
366 }
367
368 if (opts.followRedirect === undefined) {
369 opts.followRedirect = true;
370 }
371
372 if (opts.timeout) {
373 if (typeof opts.timeout === 'number') {
374 opts.gotTimeout = {request: opts.timeout};
375 } else {
376 opts.gotTimeout = opts.timeout;
377 }
378 delete opts.timeout;
379 }
380
381 return opts;
382}
383
384function got(url, opts) {
385 try {
386 return asPromise(normalizeArguments(url, opts));
387 } catch (err) {
388 return Promise.reject(err);
389 }
390}
391
392got.stream = (url, opts) => asStream(normalizeArguments(url, opts));
393
394const methods = [
395 'get',
396 'post',
397 'put',
398 'patch',
399 'head',
400 'delete'
401];
402
403for (const method of methods) {
404 got[method] = (url, opts) => got(url, Object.assign({}, opts, {method}));
405 got.stream[method] = (url, opts) => got.stream(url, Object.assign({}, opts, {method}));
406}
407
408class StdError extends Error {
409 constructor(message, error, opts) {
410 super(message);
411 this.name = 'StdError';
412
413 if (error.code !== undefined) {
414 this.code = error.code;
415 }
416
417 Object.assign(this, {
418 host: opts.host,
419 hostname: opts.hostname,
420 method: opts.method,
421 path: opts.path,
422 protocol: opts.protocol,
423 url: opts.href
424 });
425 }
426}
427
428got.RequestError = class extends StdError {
429 constructor(error, opts) {
430 super(error.message, error, opts);
431 this.name = 'RequestError';
432 }
433};
434
435got.ReadError = class extends StdError {
436 constructor(error, opts) {
437 super(error.message, error, opts);
438 this.name = 'ReadError';
439 }
440};
441
442got.ParseError = class extends StdError {
443 constructor(error, statusCode, opts, data) {
444 super(`${error.message} in "${urlLib.format(opts)}": \n${data.slice(0, 77)}...`, error, opts);
445 this.name = 'ParseError';
446 this.statusCode = statusCode;
447 this.statusMessage = http.STATUS_CODES[this.statusCode];
448 }
449};
450
451got.HTTPError = class extends StdError {
452 constructor(statusCode, headers, opts) {
453 const statusMessage = http.STATUS_CODES[statusCode];
454 super(`Response code ${statusCode} (${statusMessage})`, {}, opts);
455 this.name = 'HTTPError';
456 this.statusCode = statusCode;
457 this.statusMessage = statusMessage;
458 this.headers = headers;
459 }
460};
461
462got.MaxRedirectsError = class extends StdError {
463 constructor(statusCode, redirectUrls, opts) {
464 super('Redirected 10 times. Aborting.', {}, opts);
465 this.name = 'MaxRedirectsError';
466 this.statusCode = statusCode;
467 this.statusMessage = http.STATUS_CODES[this.statusCode];
468 this.redirectUrls = redirectUrls;
469 }
470};
471
472got.UnsupportedProtocolError = class extends StdError {
473 constructor(opts) {
474 super(`Unsupported protocol "${opts.protocol}"`, {}, opts);
475 this.name = 'UnsupportedProtocolError';
476 }
477};
478
479module.exports = got;