ethers.js/packages/web/lib/index.js

308 lines
12 KiB
JavaScript
Raw Normal View History

2019-05-15 01:48:48 +03:00
"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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
2019-06-12 08:01:04 +03:00
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
2019-05-15 01:48:48 +03:00
Object.defineProperty(exports, "__esModule", { value: true });
2019-06-12 08:25:05 +03:00
var cross_fetch_1 = __importDefault(require("cross-fetch"));
2019-05-15 01:48:48 +03:00
var base64_1 = require("@ethersproject/base64");
var properties_1 = require("@ethersproject/properties");
var strings_1 = require("@ethersproject/strings");
2019-08-02 09:10:58 +03:00
var logger_1 = require("@ethersproject/logger");
var _version_1 = require("./_version");
var logger = new logger_1.Logger(_version_1.version);
function getResponse(response) {
var headers = {};
if (response.headers.forEach) {
response.headers.forEach(function (value, key) {
headers[key.toLowerCase()] = value;
});
}
else {
((response.headers).keys)().forEach(function (key) {
headers[key.toLowerCase()] = response.headers.get(key);
});
}
return {
statusCode: response.status,
status: response.statusText,
headers: headers
};
}
2019-05-15 01:48:48 +03:00
function fetchJson(connection, json, processFunc) {
var headers = {};
var url = null;
2019-06-12 08:01:04 +03:00
// @TODO: Allow ConnectionInfo to override some of these values
var options = {
method: "GET",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
redirect: "follow",
referrer: "client",
};
2019-09-28 09:36:19 +03:00
var allow304 = false;
2019-05-15 01:48:48 +03:00
var timeout = 2 * 60 * 1000;
var throttle = 25;
if (options.throttleLimit) {
throttle = options.throttleLimit;
}
2019-05-15 01:48:48 +03:00
if (typeof (connection) === "string") {
url = connection;
}
else if (typeof (connection) === "object") {
2019-06-12 08:01:04 +03:00
if (connection == null || connection.url == null) {
2019-08-02 09:10:58 +03:00
logger.throwArgumentError("missing URL", "connection.url", connection);
2019-05-15 01:48:48 +03:00
}
url = connection.url;
if (typeof (connection.timeout) === "number" && connection.timeout > 0) {
timeout = connection.timeout;
}
if (connection.headers) {
for (var key in connection.headers) {
headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
2019-09-28 09:36:19 +03:00
if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
allow304 = true;
}
2019-05-15 01:48:48 +03:00
}
}
if (connection.user != null && connection.password != null) {
2019-06-12 08:01:04 +03:00
if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
2019-08-02 09:10:58 +03:00
logger.throwError("basic authentication requires a secure https url", logger_1.Logger.errors.INVALID_ARGUMENT, { argument: "url", url: url, user: connection.user, password: "[REDACTED]" });
2019-05-15 01:48:48 +03:00
}
var authorization = connection.user + ":" + connection.password;
headers["authorization"] = {
key: "Authorization",
value: "Basic " + base64_1.encode(strings_1.toUtf8Bytes(authorization))
};
}
}
if (json) {
options.method = "POST";
options.body = json;
headers["content-type"] = { key: "Content-Type", value: "application/json" };
}
var flatHeaders = {};
Object.keys(headers).forEach(function (key) {
var header = headers[key];
flatHeaders[header.key] = header.value;
});
options.headers = flatHeaders;
var runningTimeout = (function () {
2019-05-15 01:48:48 +03:00
var timer = null;
var promise = new Promise(function (resolve, reject) {
if (timeout) {
timer = setTimeout(function () {
if (timer == null) {
return;
}
timer = null;
reject(logger.makeError("timeout", logger_1.Logger.errors.TIMEOUT, { timeout: timeout }));
}, timeout);
}
});
var cancel = function () {
2019-05-15 01:48:48 +03:00
if (timer == null) {
return;
}
clearTimeout(timer);
timer = null;
};
return { promise: promise, cancel: cancel };
})();
if (throttle == 100) {
console.log(throttle);
}
var runningFetch = (function () {
return __awaiter(this, void 0, void 0, function () {
var response, body, error_1, json, error_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
response = null;
body = null;
_a.label = 1;
case 1:
if (!true) return [3 /*break*/, 7];
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, cross_fetch_1.default(url, options)];
case 3:
response = _a.sent();
return [3 /*break*/, 5];
case 4:
error_1 = _a.sent();
console.log(error_1);
return [3 /*break*/, 5];
case 5: return [4 /*yield*/, response.text()];
case 6:
body = _a.sent();
if (allow304 && response.status === 304) {
// Leave body as null
return [3 /*break*/, 7];
}
else if (!response.ok) {
runningTimeout.cancel();
logger.throwError("bad response", logger_1.Logger.errors.SERVER_ERROR, {
status: response.status,
body: body,
type: response.type,
url: response.url
2019-09-28 09:36:19 +03:00
});
}
else {
return [3 /*break*/, 7];
2019-09-28 09:36:19 +03:00
}
return [3 /*break*/, 1];
case 7:
runningTimeout.cancel();
json = null;
if (body != null) {
try {
json = JSON.parse(body);
}
catch (error) {
logger.throwError("invalid JSON", logger_1.Logger.errors.SERVER_ERROR, {
body: body,
error: error,
url: url
});
}
}
if (!processFunc) return [3 /*break*/, 11];
_a.label = 8;
case 8:
_a.trys.push([8, 10, , 11]);
return [4 /*yield*/, processFunc(json, getResponse(response))];
case 9:
json = _a.sent();
return [3 /*break*/, 11];
case 10:
error_2 = _a.sent();
2019-09-28 09:36:19 +03:00
logger.throwError("processing response error", logger_1.Logger.errors.SERVER_ERROR, {
body: json,
error: error_2
2019-09-28 09:36:19 +03:00
});
return [3 /*break*/, 11];
case 11: return [2 /*return*/, json];
2019-05-15 01:48:48 +03:00
}
2019-09-28 09:36:19 +03:00
});
2019-06-12 08:01:04 +03:00
});
})();
return Promise.race([runningTimeout.promise, runningFetch]);
2019-05-15 01:48:48 +03:00
}
exports.fetchJson = fetchJson;
function poll(func, options) {
if (!options) {
options = {};
}
options = properties_1.shallowCopy(options);
if (options.floor == null) {
options.floor = 0;
}
if (options.ceiling == null) {
options.ceiling = 10000;
}
if (options.interval == null) {
options.interval = 250;
}
return new Promise(function (resolve, reject) {
var timer = null;
var done = false;
// Returns true if cancel was successful. Unsuccessful cancel means we're already done.
var cancel = function () {
if (done) {
return false;
}
done = true;
if (timer) {
clearTimeout(timer);
}
return true;
};
if (options.timeout) {
timer = setTimeout(function () {
if (cancel()) {
reject(new Error("timeout"));
}
}, options.timeout);
}
var retryLimit = options.retryLimit;
var attempt = 0;
function check() {
return func().then(function (result) {
// If we have a result, or are allowed null then we're done
if (result !== undefined) {
if (cancel()) {
resolve(result);
}
}
else if (options.onceBlock) {
options.onceBlock.once("block", check);
// Otherwise, exponential back-off (up to 10s) our next request
}
else if (!done) {
attempt++;
if (attempt > retryLimit) {
if (cancel()) {
reject(new Error("retry limit reached"));
}
return;
}
var timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
if (timeout < options.floor) {
timeout = options.floor;
}
if (timeout > options.ceiling) {
timeout = options.ceiling;
}
setTimeout(check, timeout);
}
return null;
}, function (error) {
if (cancel()) {
reject(error);
}
});
}
check();
});
}
exports.poll = poll;