Skip to content

Commit

Permalink
Fixes for dist builds without injected XMLHttpRequest (#789, #506).
Browse files Browse the repository at this point in the history
  • Loading branch information
ricmoo committed Apr 18, 2020
1 parent 723249d commit 9ae6b70
Show file tree
Hide file tree
Showing 8 changed files with 215 additions and 85 deletions.
2 changes: 1 addition & 1 deletion packages/providers/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"author": "Richard Moore <me@ricmoo.com>",
"browser": {
"./ipc-provider": "./lib/browser-ipc-provider.js",
"./lib/ipc-provider": "./lib/browser-ipc-provider.js",
"net": "./lib/browser-net.js",
"ws": "./lib/browser-ws.js"
},
Expand Down
7 changes: 5 additions & 2 deletions packages/providers/src.ts/browser-ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";

let WS = (WebSocket as any);
let WS: any = null;

if (WS == null) {
try {
WS = (WebSocket as any);
if (WS == null) { throw new Error("inject please"); }
} catch (error) {
const logger = new Logger(version);
WS = function() {
logger.throwError("WebSockets not supported in this environment", Logger.errors.UNSUPPORTED_OPERATION, {
Expand Down
6 changes: 4 additions & 2 deletions packages/web/package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
{
"author": "Richard Moore <me@ricmoo.com>",
"browser": {
"./lib/geturl": "./lib/browser-geturl.js"
},
"dependencies": {
"@ethersproject/base64": ">=5.0.0-beta.126",
"@ethersproject/logger": ">=5.0.0-beta.129",
"@ethersproject/properties": ">=5.0.0-beta.131",
"@ethersproject/strings": ">=5.0.0-beta.130",
"cross-fetch": "3.0.4"
"@ethersproject/strings": ">=5.0.0-beta.130"
},
"description": "Utility fucntions for managing web requests for ethers.",
"ethereum": "donations.ethers.eth",
Expand Down
51 changes: 51 additions & 0 deletions packages/web/src.ts/browser-geturl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"use strict";

export type GetUrlResponse = {
statusCode: number,
statusMessage: string;
headers: { [ key: string] : string };
body: string;
};

export type Options = {
method?: string,
body?: string
headers?: { [ key: string] : string },
};

export async function getUrl(href: string, options?: Options): Promise<GetUrlResponse> {
if (options == null) { options = { }; }

const request = {
method: (options.method || "GET"),
headers: (options.headers || { }),
body: (options.body || undefined),

mode: <RequestMode>"cors", // no-cors, cors, *same-origin
cache: <RequestCache>"no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: <RequestCredentials>"same-origin", // include, *same-origin, omit
redirect: <RequestRedirect>"follow", // manual, *follow, error
referrer: "client", // no-referrer, *client
};

const response = await fetch(href, request);
const body = await response.text();

const headers: { [ name: string ]: string } = { };
if (response.headers.forEach) {
response.headers.forEach((value, key) => {
headers[key.toLowerCase()] = value;
});
} else {
(<() => Array<string>>((<any>(response.headers)).keys))().forEach((key) => {
headers[key.toLowerCase()] = response.headers.get(key);
});
}

return {
headers: headers,
statusCode: response.status,
statusMessage: response.statusText,
body: body,
}
}
95 changes: 95 additions & 0 deletions packages/web/src.ts/geturl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"use strict";

import http from "http";
import https from "https";
import { URL } from "url"

import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);

export type GetUrlResponse = {
statusCode: number,
statusMessage: string;
headers: { [ key: string] : string };
body: string;
};

export type Options = {
method?: string,
body?: string
headers?: { [ key: string] : string },
};

function getResponse(request: http.ClientRequest): Promise<GetUrlResponse> {
return new Promise((resolve, reject) => {
request.once("response", (resp: http.IncomingMessage) => {
const response: GetUrlResponse = {
statusCode: resp.statusCode,
statusMessage: resp.statusMessage,
headers: Object.keys(resp.headers).reduce((accum, name) => {
let value = resp.headers[name];
if (Array.isArray(value)) {
value = value.join(", ");
}
accum[name] = value;
return accum;
}, <{ [ name: string ]: string }>{ }),
body: null
};
resp.setEncoding("utf8");

resp.on("data", (chunk: string) => {
if (response.body == null) { response.body = ""; }
response.body += chunk;
});

resp.on("end", () => {
resolve(response);
});

resp.on("error", (error) => {
(<any>error).response = response;
reject(error);
});
});

request.on("error", (error) => { reject(error); });
});
}

export async function getUrl(href: string, options?: Options): Promise<GetUrlResponse> {
if (options == null) { options = { }; }

const url = new URL(href);

const request = {
method: (options.method || "GET"),
headers: (options.headers || { }),
};

let req: http.ClientRequest = null;
switch (url.protocol) {
case "http:": {
req = http.request(url, request);
break;
}
case "https:":
req = https.request(url, request);
break;
default:
logger.throwError(`unsupported protocol ${ url.protocol }`, Logger.errors.UNSUPPORTED_OPERATION, {
protocol: url.protocol,
operation: "request"
});
}

if (options.body) {
req.write(options.body);
}
req.end();

const response = await getResponse(req);
return response;
}

72 changes: 21 additions & 51 deletions packages/web/src.ts/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"use strict";

import fetch from "cross-fetch";

import { encode as base64Encode } from "@ethersproject/base64";
import { shallowCopy } from "@ethersproject/properties";
import { toUtf8Bytes } from "@ethersproject/strings";
Expand All @@ -10,6 +8,8 @@ import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);

import { getUrl, GetUrlResponse } from "./geturl";

// Exported Types
export type ConnectionInfo = {
url: string,
Expand All @@ -36,31 +36,12 @@ export type PollOptions = {

export type FetchJsonResponse = {
statusCode: number;
status: string;
headers: { [ header: string ]: string };
};


type Header = { key: string, value: string };

function getResponse(response: Response): FetchJsonResponse {
const headers: { [ header: string ]: string } = { };
if (response.headers.forEach) {
response.headers.forEach((value, key) => {
headers[key.toLowerCase()] = value;
});
} else {
(<() => Array<string>>((<any>(response.headers)).keys))().forEach((key) => {
headers[key.toLowerCase()] = response.headers.get(key);
});
}

return {
statusCode: response.status,
status: response.statusText,
headers: headers
};
}
export function fetchJson(connection: string | ConnectionInfo, json?: string, processFunc?: (value: any, response: FetchJsonResponse) => any): Promise<any> {
const headers: { [key: string]: Header } = { };

Expand All @@ -69,11 +50,6 @@ export function fetchJson(connection: string | ConnectionInfo, json?: string, pr
// @TODO: Allow ConnectionInfo to override some of these values
const options: any = {
method: "GET",
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
redirect: "follow", // manual, *follow, error
referrer: "client", // no-referrer, *client
};

let allow304 = false;
Expand Down Expand Up @@ -157,33 +133,27 @@ export function fetchJson(connection: string | ConnectionInfo, json?: string, pr

const runningFetch = (async function() {

let response: Response = null;
let body: string = null;

while (true) {
try {
response = await fetch(url, options);
} catch (error) {
console.log(error);
}
body = await response.text();
let response: GetUrlResponse = null;
try {
response = await getUrl(url, options);
} catch (error) {
console.log(error);
response = (<any>error).response;
}

if (allow304 && response.status === 304) {
body = null;
break;
let body = response.body;

} else if (!response.ok) {
runningTimeout.cancel();
logger.throwError("bad response", Logger.errors.SERVER_ERROR, {
status: response.status,
body: body,
type: response.type,
url: response.url
});
if (allow304 && response.statusCode === 304) {
body = null;

} else {
break;
}
} else if (response.statusCode < 200 || response.statusCode >= 300) {
runningTimeout.cancel();
logger.throwError("bad response", Logger.errors.SERVER_ERROR, {
status: response.statusCode,
headers: response.headers,
body: body,
url: url
});
}

runningTimeout.cancel();
Expand All @@ -203,7 +173,7 @@ export function fetchJson(connection: string | ConnectionInfo, json?: string, pr

if (processFunc) {
try {
json = await processFunc(json, getResponse(response));
json = await processFunc(json, response);
} catch (error) {
logger.throwError("processing response error", Logger.errors.SERVER_ERROR, {
body: json,
Expand Down
19 changes: 3 additions & 16 deletions packages/web/thirdparty.d.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
declare module "xmlhttprequest" {
export class XMLHttpRequest {
readyState: number;
status: number;
responseText: string;

constructor();
open(method: string, url: string, async?: boolean): void;
setRequestHeader(key: string, value: string): void;
send(body?: string): void;
abort(): void;

onreadystatechange: () => void;
onerror: (error: Error) => void;
}
declare module "node-fetch" {
function fetch(url: string, options: any): Promise<Response>;
export default fetch;
}

Loading

0 comments on commit 9ae6b70

Please sign in to comment.