add probing for active switcher when not found

This commit is contained in:
Percs 2024-05-03 16:18:31 -05:00
parent 84827c9541
commit 80368ba682
2 changed files with 19 additions and 5 deletions

View file

@ -1,6 +1,6 @@
{
"name": "@mercuryworkshop/bare-mux",
"version": "1.0.9",
"version": "1.1.0",
"description": "",
"type": "module",
"scripts": {

View file

@ -29,13 +29,15 @@ function initTransport(name: string, config: any) {
return cl;
}
class Switcher {
active: BareTransport | null = null;
active: BareTransport | null = null
channel = new BroadcastChannel("bare-mux");
data: Object | null = null
constructor() {
this.channel.addEventListener("message", ({ data: { type, data } }) => {
console.log(type, data, "ServiceWorker" in globalThis);
console.log(`bare-mux: ${type}`, data, `${"ServiceWorker" in globalThis}`);
switch (type) {
case "setremote":
this.active = new RemoteTransport
@ -44,15 +46,24 @@ class Switcher {
const { name, config } = data;
this.active = initTransport(name, config);
break;
case "find":
if (this.data) {
this.channel.postMessage(this.data)
}
break;
}
});
}
}
export function findSwitcher(): Switcher {
if ("ServiceWorkerGlobalScope" in globalThis && globalThis.gSwitcher && !globalThis.gSwitcher.active) {
globalThis.gSwitcher.channel.postMessage({ type: "find" })
}
if (globalThis.gSwitcher) return globalThis.gSwitcher;
if ("ServiceWorkerGlobalScope" in globalThis) {
globalThis.gSwitcher = new Switcher;
globalThis.gSwitcher.channel.postMessage({ type: "find" })
return globalThis.gSwitcher;
}
@ -72,6 +83,7 @@ export function findSwitcher(): Switcher {
}
} catch (e) {
globalThis.gSwitcher = new Switcher;
globalThis.gSwitcher.channel.postMessage({ type: "find" })
return globalThis.gSwitcher;
}
}
@ -83,12 +95,14 @@ findSwitcher();
export function SetTransport(name: string, ...config: any[]) {
let switcher = findSwitcher();
switcher.active = initTransport(name, config);
switcher.channel.postMessage({ type: "set", data: { name, config } });
switcher.data = { type: "set", data: { name, config } }
switcher.channel.postMessage(switcher.data);
}
export async function SetSingletonTransport(client: BareTransport) {
let switcher = findSwitcher();
await client.init();
switcher.active = client;
switcher.channel.postMessage({ type: "setremote" });
switcher.data = { type: "setremote", data: { name: client.constructor.name }}
switcher.channel.postMessage(switcher.data);
}