76 lines
No EOL
2.9 KiB
JavaScript
76 lines
No EOL
2.9 KiB
JavaScript
"use strict";
|
|
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
return new (P || (P = Promise))(function (resolve, reject) {
|
|
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
});
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.tall = exports.locationHeaderPlugin = exports.Stop = exports.Follow = void 0;
|
|
const http_1 = require("http");
|
|
const https_1 = require("https");
|
|
class Follow {
|
|
constructor(follow) {
|
|
this.follow = follow;
|
|
}
|
|
}
|
|
exports.Follow = Follow;
|
|
class Stop {
|
|
constructor(stop) {
|
|
this.stop = stop;
|
|
}
|
|
}
|
|
exports.Stop = Stop;
|
|
function locationHeaderPlugin(url, response, previous) {
|
|
return __awaiter(this, void 0, void 0, function* () {
|
|
const { protocol, host } = url;
|
|
if (response.headers.location) {
|
|
const followUrl = new URL(response.headers.location.startsWith('http')
|
|
? response.headers.location
|
|
: `${protocol}//${host}${response.headers.location}`);
|
|
return new Follow(followUrl);
|
|
}
|
|
return previous;
|
|
});
|
|
}
|
|
exports.locationHeaderPlugin = locationHeaderPlugin;
|
|
const defaultOptions = {
|
|
method: 'GET',
|
|
maxRedirects: 3,
|
|
headers: {},
|
|
timeout: 120000,
|
|
plugins: [locationHeaderPlugin]
|
|
};
|
|
function makeRequest(url, options) {
|
|
return new Promise((resolve, reject) => {
|
|
const request = url.protocol === 'https:' ? https_1.request : http_1.request;
|
|
const req = request(url, options, (response) => {
|
|
resolve(response);
|
|
});
|
|
req.on('error', reject);
|
|
req.setTimeout(options.timeout, () => req.destroy());
|
|
req.end();
|
|
});
|
|
}
|
|
const tall = (url, options) => __awaiter(void 0, void 0, void 0, function* () {
|
|
const opt = Object.assign({}, defaultOptions, options);
|
|
if (opt.maxRedirects <= 0) {
|
|
return url.toString();
|
|
}
|
|
const parsedUrl = new URL(url);
|
|
let prev = new Stop(parsedUrl);
|
|
const response = yield makeRequest(parsedUrl, opt);
|
|
for (const plugin of opt.plugins) {
|
|
prev = yield plugin(parsedUrl, response, prev);
|
|
}
|
|
const maxRedirects = opt.maxRedirects - 1;
|
|
if (prev instanceof Follow) {
|
|
return yield (0, exports.tall)(prev.follow.toString(), Object.assign(Object.assign({}, options), { maxRedirects }));
|
|
}
|
|
return prev.stop.toString();
|
|
});
|
|
exports.tall = tall;
|
|
//# sourceMappingURL=index.js.map
|