From caccb62424da57fdef1e5c79a58110247fd63d6a Mon Sep 17 00:00:00 2001 From: Martin Varmuza Date: Tue, 11 Feb 2025 08:53:51 +0100 Subject: [PATCH] custom sharedworker --- .../src/sessions/background-browser.ts | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/packages/transport/src/sessions/background-browser.ts b/packages/transport/src/sessions/background-browser.ts index a63bf9e79c2..fd413fc88c4 100644 --- a/packages/transport/src/sessions/background-browser.ts +++ b/packages/transport/src/sessions/background-browser.ts @@ -2,6 +2,42 @@ import type { Descriptor } from '../types'; import { SessionsBackground } from './background'; import { HandleMessageParams, HandleMessageResponse, SessionsBackgroundInterface } from './types'; +class CustomSharedWorker extends SharedWorker { + constructor(scriptURL: string | URL, options?: WorkerOptions) { + const url = String(scriptURL); + super( + // Check if the URL is remote + url.includes('://') && !url.startsWith(location.origin) + ? // Launch the worker with an inline script that will use `importScripts` + // to bootstrap the actual script to work around the same origin policy. + URL.createObjectURL( + new Blob( + [ + // Replace the `importScripts` function with + // a patched version that will resolve relative URLs + // to the remote script URL. + // + // Without a patched `importScripts` Webpack 5 generated worker chunks will fail with the following error: + // + // Uncaught (in promise) DOMException: Failed to execute 'importScripts' on 'WorkerGlobalScope': + // The script at 'http://some.domain/worker.1e0e1e0e.js' failed to load. + // + // For minification, the inlined variable names are single letters: + // i = original importScripts + // a = arguments + // u = URL + `importScripts=((i)=>(...a)=>i(...a.map((u)=>''+new URL(u,"${url}"))))(importScripts);importScripts("${url}")`, + ], + { type: 'text/javascript' }, + ), + ) + : scriptURL, + options, + ); + } +} + +export {}; /** * creating BrowserSessionsBackground initiates sessions-background for browser based environments and provides: * - `handleMessage` which is used to send messages to sessions background @@ -14,7 +50,7 @@ export class BrowserSessionsBackground implements SessionsBackgroundInterface { private readonly background; constructor(sessionsBackgroundUrl: string) { - this.background = new SharedWorker(sessionsBackgroundUrl, { + this.background = new CustomSharedWorker(sessionsBackgroundUrl, { name: '@trezor/connect-web transport sessions worker', }); }