-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
79 lines (67 loc) · 2.01 KB
/
Copy pathclient.js
File metadata and controls
79 lines (67 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// BunTop client library - injected into the webview on load.
(() => {
const pending = new Map();
let nextId = 1;
let ws;
let reconnectDelay = 500;
function connect() {
ws = new WebSocket(`ws://127.0.0.1:__BUNTOP_PORT__/__buntop_ws`);
ws.addEventListener("open", () => {
reconnectDelay = 500;
});
ws.addEventListener("message", (event) => {
const msg = JSON.parse(event.data);
if (msg.type === "response") {
const entry = pending.get(msg.id);
if (!entry) return;
pending.delete(msg.id);
if (msg.error) entry.reject(new Error(msg.error));
else entry.resolve(msg.result);
return;
}
if (msg.type === "event") {
window.dispatchEvent(new CustomEvent(`buntop:${msg.event}`, { detail: msg.data }));
if (msg.event === "second-instance") window.focus();
}
});
ws.addEventListener("close", () => {
for (const { reject } of pending.values()) reject(new Error("Connection closed"));
pending.clear();
setTimeout(connect, reconnectDelay);
reconnectDelay = Math.min(reconnectDelay * 2, 5000);
});
}
connect();
function ready() {
return new Promise((resolve) => {
if (ws.readyState === WebSocket.OPEN) resolve();
else ws.addEventListener("open", () => resolve(), { once: true });
});
}
async function call(name, ...args) {
await ready();
const id = nextId++;
return new Promise((resolve, reject) => {
pending.set(id, { resolve, reject });
ws.send(JSON.stringify({ type: "call", id, name, args }));
});
}
function getSize() {
return { width: window.outerWidth, height: window.outerHeight };
}
function getInnerSize() {
return { width: window.innerWidth, height: window.innerHeight };
}
function getPosition() {
return { x: window.screenX, y: window.screenY };
}
window.buntop = {
info: __BUNTOP_INFO__,
call,
ready,
getSize,
getInnerSize,
getPosition,
close: () => window.close(),
};
})();