n8n-nodes-wax
Version:
n8n Community Node Package for the WAX Blockchain
86 lines (85 loc) • 3.74 kB
JavaScript
;
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 });
class WaxEventSource {
constructor(waxSigningURL = "http://localhost:3000") {
this.waxSigningURL = waxSigningURL;
this.timeout = () => {
return new Promise((resolve, reject) => {
const wait = setTimeout(() => {
clearTimeout(wait);
reject(new Error("Timeout"));
}, 2000);
});
};
this.openEventSource = this.openEventSource.bind(this);
this.onceEvent = this.onceEvent.bind(this);
}
openEventSource(url, message, win) {
return __awaiter(this, void 0, void 0, function* () {
const openedWindow = win
? win
: yield window.open(url, "WaxPopup", "height=800,width=600");
if (!openedWindow) {
throw new Error("Unable to open a popup window");
}
if (typeof message === "undefined") {
return openedWindow;
}
const postTransaction = (event) => __awaiter(this, void 0, void 0, function* () {
if (event.data.type === "READY") {
// @ts-ignore
openedWindow.postMessage(message, this.waxSigningURL);
}
});
const eventPromise = this.onceEvent(
// @ts-ignore
openedWindow, this.waxSigningURL, postTransaction);
yield Promise.race([eventPromise, this.timeout()]).catch(err => {
if (err.message !== "Timeout") {
throw err;
}
openedWindow.postMessage(message, this.waxSigningURL);
});
return openedWindow;
});
}
onceEvent(source, origin, action) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
window.addEventListener("message", function onEvent(event) {
return __awaiter(this, void 0, void 0, function* () {
// Validate expected origin for event
if (event.origin !== origin) {
return;
}
// Validate expected source for event
if (event.source !== source) {
return;
}
if (typeof event.data !== "object") {
return;
}
try {
const result = yield action(event);
resolve(result);
}
catch (e) {
reject(e);
}
window.removeEventListener("message", onEvent, false);
});
}, false);
});
});
}
}
exports.WaxEventSource = WaxEventSource;