From 6092b3d17456b6e34d9ab93064b7778010aac0ef Mon Sep 17 00:00:00 2001 From: Paulo Koch Date: Thu, 5 Dec 2024 19:21:33 +0000 Subject: [PATCH] fix: less recursion --- .../lib/enclave-providers/iframe-enclave.ts | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/packages/idos-sdk-js/src/lib/enclave-providers/iframe-enclave.ts b/packages/idos-sdk-js/src/lib/enclave-providers/iframe-enclave.ts index b4feef3af..84057824b 100644 --- a/packages/idos-sdk-js/src/lib/enclave-providers/iframe-enclave.ts +++ b/packages/idos-sdk-js/src/lib/enclave-providers/iframe-enclave.ts @@ -110,15 +110,10 @@ export class IframeEnclave implements EnclaveProvider { }) as Promise; } - async #loadEnclave(): Promise { - const container = document.querySelector(this.container); - const iframeElem = document.getElementById(this.iframe.id); - - if (iframeElem) { - console.warn("An Iframe already exists in the container"); - container?.removeChild(iframeElem); - return new Promise((resolve) => this.#loadEnclave().then(resolve)); - } + async #loadEnclave(): Promise { + const container = + document.querySelector(this.container) || + throwNew(Error, `Can't find container with selector ${this.container}`); // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy#directives const permissionsPolicies = ["publickey-credentials-get", "storage-access"]; @@ -152,11 +147,15 @@ export class IframeEnclave implements EnclaveProvider { this.iframe.style.setProperty(k, v); } - if (!container) throw new Error(`Can't find container with selector ${this.container}`); - - container.appendChild(this.iframe); + // This was the best way we found at the time to check if we had already + // added the element to the tree. + if (!document.getElementById(this.iframe.id)) { + container.appendChild(this.iframe); + } - return new Promise((resolve) => this.iframe.addEventListener("load", () => resolve())); + return new Promise((resolve) => + this.iframe.addEventListener("load", () => resolve(), { once: true }), + ); } #showEnclave() { @@ -240,3 +239,7 @@ export class IframeEnclave implements EnclaveProvider { }; } } + +function throwNew(ErrorClass: ErrorConstructor, ...args: Parameters): never { + throw new ErrorClass(...args); +}