wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
exports.__esModule = true;
var cacheUtils = require("./cache-utils");
var FileCache_1 = require("./FileCache");
var MemoryCache_1 = require("./MemoryCache");
var http_1 = require("http");
var zlib_1 = require("zlib");
var url_1 = require("url");
var stream_1 = require("stream");
var https_1 = require("https");
var Response = require("http-response-object");
exports.Response = Response;
var caseless = require('caseless');
var fileCache = new FileCache_1["default"](__dirname + '/cache');
var memoryCache = new MemoryCache_1["default"]();
function requestProtocol(protocol, options, callback) {
    if (protocol === 'http') {
        return http_1.request(options, callback);
    }
    else if (protocol === 'https') {
        return https_1.request(options, callback);
    }
    throw new Error('Unsupported protocol ' + protocol);
}
function request(method, url, options, callback) {
    if (typeof options === 'function') {
        callback = options;
        options = null;
    }
    if (options === null || options === undefined) {
        options = {};
    }
    if (typeof options !== 'object') {
        throw new TypeError('options must be an object (or null)');
    }
    if (typeof callback !== 'function') {
        throw new TypeError('callback must be a function');
    }
    return _request(method, ((url && typeof url === 'object') ? url.href : url), options, callback);
}
function _request(method, url, options, callback) {
    var start = Date.now();
    if (typeof method !== 'string') {
        throw new TypeError('The method must be a string.');
    }
    if (typeof url !== 'string') {
        throw new TypeError('The URL/path must be a string or a URL object.');
    }
    method = method.toUpperCase();
    var urlObject = url_1.parse(url);
    var protocol = (urlObject.protocol || '').replace(/\:$/, '');
    if (protocol !== 'http' && protocol !== 'https') {
        throw new TypeError('The protocol "' + protocol + '" is not supported, cannot load "' + url + '"');
    }
    var rawHeaders = options.headers || {};
    var headers = caseless(rawHeaders);
    if (urlObject.auth) {
        headers.set('Authorization', 'Basic ' + (Buffer.from(urlObject.auth)).toString('base64'));
    }
    var agent = 'agent' in options ? options.agent : false;
    var cache = options.cache;
    if (typeof cache === 'string') {
        if (cache === 'file') {
            cache = fileCache;
        }
        else if (cache === 'memory') {
            cache = memoryCache;
        }
    }
    if (cache && !(typeof cache === 'object' && typeof cache.getResponse === 'function' && typeof cache.setResponse === 'function' && typeof cache.invalidateResponse === 'function')) {
        throw new TypeError(cache + ' is not a valid cache, caches must have `getResponse`, `setResponse` and `invalidateResponse` methods.');
    }
    var ignoreFailedInvalidation = options.ignoreFailedInvalidation;
    if (options.duplex !== undefined && typeof options.duplex !== 'boolean') {
        throw new Error('expected options.duplex to be a boolean if provided');
    }
    var duplex = options.duplex !== undefined ? options.duplex : !(method === 'GET' || method === 'DELETE' || method === 'HEAD');
    var unsafe = !(method === 'GET' || method === 'OPTIONS' || method === 'HEAD');
    if (options.gzip) {
        headers.set('Accept-Encoding', headers.has('Accept-Encoding') ? headers.get('Accept-Encoding') + ',gzip,deflate' : 'gzip,deflate');
        return _request(method, url, {
            allowRedirectHeaders: options.allowRedirectHeaders,
            duplex: duplex,
            headers: rawHeaders,
            agent: agent,
            followRedirects: options.followRedirects,
            retry: options.retry,
            retryDelay: options.retryDelay,
            maxRetries: options.maxRetries,
            cache: cache,
            timeout: options.timeout
        }, function (err, res) {
            if (err)
                return callback(err);
            if (!res)
                return callback(new Error('Response should not be undefined if there is no error.'));
            var newHeaders = __assign({}, res.headers);
            var newBody = res.body;
            switch (newHeaders['content-encoding']) {
                case 'gzip':
                    delete newHeaders['content-encoding'];
                    newBody = res.body.pipe(zlib_1.createGunzip());
                    break;
                case 'deflate':
                    delete newHeaders['content-encoding'];
                    newBody = res.body.pipe(zlib_1.createInflate());
                    break;
            }
            return callback(err, new Response(res.statusCode, newHeaders, newBody, res.url));
        });
    }
    if (options.followRedirects) {
        return _request(method, url, {
            allowRedirectHeaders: options.allowRedirectHeaders,
            duplex: duplex,
            headers: rawHeaders,
            agent: agent,
            retry: options.retry,
            retryDelay: options.retryDelay,
            maxRetries: options.maxRetries,
            cache: cache,
            timeout: options.timeout
        }, function (err, res) {
            if (err)
                return callback(err);
            if (!res)
                return callback(new Error('Response should not be undefined if there is no error.'));
            if (options.followRedirects && isRedirect(res.statusCode)) {
                // prevent leakage of file handles
                res.body.resume();
                if (method === 'DELETE' && res.statusCode === 303) {
                    // 303 See Other should convert to GET for duplex
                    // requests and for DELETE
                    method = 'GET';
                }
                if (options.maxRedirects === 0) {
                    var err_1 = new Error('Maximum number of redirects exceeded');
                    err_1.res = res;
                    return callback(err_1, res);
                }
                options = __assign({}, options, { duplex: false, maxRedirects: options.maxRedirects && options.maxRedirects !== Infinity ? options.maxRedirects - 1 : options.maxRedirects });
                // don't maintain headers through redirects
                // This fixes a problem where a POST to http://example.com
                // might result in a GET to http://example.co.uk that includes "content-length"
                // as a header
                var headers_1 = caseless(options.headers);
                var redirectHeaders = {};
                if (options.allowRedirectHeaders) {
                    for (var i = 0; i < options.allowRedirectHeaders.length; i++) {
                        var headerName = options.allowRedirectHeaders[i];
                        var headerValue = headers_1.get(headerName);
                        if (headerValue) {
                            redirectHeaders[headerName] = headerValue;
                        }
                    }
                }
                options.headers = redirectHeaders;
                var location = res.headers.location;
                if (typeof location !== 'string') {
                    return callback(new Error('Cannot redirect to non string location: ' + location));
                }
                return request(duplex ? 'GET' : method, url_1.resolve(url, location), options, callback);
            }
            else {
                return callback(null, res);
            }
        });
    }
    if (cache && method === 'GET' && !duplex) {
        var timestamp_1 = Date.now();
        return cache.getResponse(url, function (err, cachedResponse) {
            if (err) {
                console.warn('Error reading from cache: ' + err.message);
            }
            var isMatch = !!(cachedResponse && cacheUtils.isMatch(rawHeaders, cachedResponse));
            if (cachedResponse && (options.isMatch ? options.isMatch(rawHeaders, cachedResponse, isMatch) : isMatch)) {
                var isExpired = cacheUtils.isExpired(cachedResponse);
                if (!(options.isExpired ? options.isExpired(cachedResponse, isExpired) : isExpired)) {
                    var res = new Response(cachedResponse.statusCode, cachedResponse.headers, cachedResponse.body, url);
                    res.fromCache = true;
                    res.fromNotModified = false;
                    return callback(null, res);
                }
                else {
                    if (cachedResponse.headers['etag']) {
                        headers.set('If-None-Match', cachedResponse.headers['etag']);
                    }
                    if (cachedResponse.headers['last-modified']) {
                        headers.set('If-Modified-Since', cachedResponse.headers['last-modified']);
                    }
                }
            }
            request('GET', url, {
                allowRedirectHeaders: options.allowRedirectHeaders,
                headers: rawHeaders,
                retry: options.retry,
                retryDelay: options.retryDelay,
                maxRetries: options.maxRetries,
                agent: agent,
                timeout: options.timeout
            }, function (err, res) {
                if (err)
                    return callback(err);
                if (!res)
                    return callback(new Error('Response should not be undefined if there is no error.'));
                if (res.statusCode === 304 && cachedResponse) { // Not Modified
                    // prevent leakage of file handles
                    res.body.resume();
                    var resultBody = cachedResponse.body;
                    var c = cache;
                    if (c.updateResponseHeaders) {
                        c.updateResponseHeaders(url, {
                            headers: res.headers,
                            requestTimestamp: timestamp_1
                        });
                    }
                    else {
                        var cachedResponseBody_1 = new stream_1.PassThrough();
                        var newResultBody_1 = new stream_1.PassThrough();
                        resultBody.on('data', function (data) {
                            cachedResponseBody_1.write(data);
                            newResultBody_1.write(data);
                        });
                        resultBody.on('end', function () {
                            cachedResponseBody_1.end();
                            newResultBody_1.end();
                        });
                        resultBody = newResultBody_1;
                        cache.setResponse(url, {
                            statusCode: cachedResponse.statusCode,
                            headers: res.headers,
                            body: cachedResponseBody_1,
                            requestHeaders: cachedResponse.requestHeaders,
                            requestTimestamp: timestamp_1
                        });
                    }
                    var response = new Response(cachedResponse.statusCode, cachedResponse.headers, resultBody, url);
                    response.fromCache = true;
                    response.fromNotModified = true;
                    return callback(null, response);
                }
                // prevent leakage of file handles
                cachedResponse && cachedResponse.body.resume();
                var canCache = cacheUtils.canCache(res);
                if (options.canCache ? options.canCache(res, canCache) : canCache) {
                    var cachedResponseBody_2 = new stream_1.PassThrough();
                    var resultResponseBody_1 = new stream_1.PassThrough();
                    res.body.on('data', function (data) {
                        cachedResponseBody_2.write(data);
                        resultResponseBody_1.write(data);
                    });
                    res.body.on('end', function () { cachedResponseBody_2.end(); resultResponseBody_1.end(); });
                    var resultResponse = new Response(res.statusCode, res.headers, resultResponseBody_1, url);
                    cache.setResponse(url, {
                        statusCode: res.statusCode,
                        headers: res.headers,
                        body: cachedResponseBody_2,
                        requestHeaders: rawHeaders,
                        requestTimestamp: timestamp_1
                    });
                    return callback(null, resultResponse);
                }
                else {
                    return callback(null, res);
                }
            });
        });
    }
    function attempt(n) {
        return _request(method, url, {
            allowRedirectHeaders: options.allowRedirectHeaders,
            headers: rawHeaders,
            agent: agent,
            timeout: options.timeout
        }, function (err, res) {
            var retry = err || !res || res.statusCode >= 400;
            if (typeof options.retry === 'function') {
                retry = options.retry(err, res, n + 1);
            }
            if (n >= (options.maxRetries || 5)) {
                retry = false;
            }
            if (retry) {
                var delay = options.retryDelay;
                if (typeof delay === 'function') {
                    delay = delay(err, res, n + 1);
                }
                delay = delay || 200;
                setTimeout(function () {
                    attempt(n + 1);
                }, delay);
            }
            else {
                callback(err, res);
            }
        });
    }
    if (options.retry && method === 'GET' && !duplex) {
        return attempt(0);
    }
    var responded = false;
    var timeout = null;
    var req = requestProtocol(protocol, {
        host: urlObject.hostname,
        port: urlObject.port == null ? undefined : +urlObject.port,
        path: urlObject.path,
        method: method,
        headers: rawHeaders,
        agent: agent
    }, function (res) {
        var end = Date.now();
        if (responded)
            return res.resume();
        responded = true;
        if (timeout !== null)
            clearTimeout(timeout);
        var result = new Response(res.statusCode || 0, res.headers, res, url);
        if (cache && unsafe && res.statusCode && res.statusCode < 400) {
            cache.invalidateResponse(url, function (err) {
                if (err && !ignoreFailedInvalidation) {
                    callback(new Error('Error invalidating the cache for' + url + ': ' + err.message), result);
                }
                else {
                    callback(null, result);
                }
            });
        }
        else {
            callback(null, result);
        }
    }).on('error', function (err) {
        if (responded)
            return;
        responded = true;
        if (timeout !== null)
            clearTimeout(timeout);
        callback(err);
    });
    function onTimeout() {
        if (responded)
            return;
        responded = true;
        if (timeout !== null)
            clearTimeout(timeout);
        req.abort();
        var duration = Date.now() - start;
        var err = new Error('Request timed out after ' + duration + 'ms');
        err.timeout = true;
        err.duration = duration;
        callback(err);
    }
    if (options.socketTimeout) {
        req.setTimeout(options.socketTimeout, onTimeout);
    }
    if (options.timeout) {
        timeout = setTimeout(onTimeout, options.timeout);
    }
    if (duplex) {
        return req;
    }
    else {
        req.end();
    }
    return undefined;
}
function isRedirect(statusCode) {
    return statusCode === 301 || statusCode === 302 || statusCode === 303 || statusCode === 307 || statusCode === 308;
}
exports["default"] = request;
module.exports = request;
module.exports["default"] = request;
module.exports.Response = Response;