forked from jae-jae/Userscript-Plus
-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmu-hermes.js
More file actions
81 lines (79 loc) · 2.06 KB
/
Copy pathmu-hermes.js
File metadata and controls
81 lines (79 loc) · 2.06 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
80
81
'use strict';
userjs.hermes = {
port: null,
msgIdGenerator: 1,
pending: new Map(),
shuttingDown: false,
shutdown: function () {
this.shuttingDown = true;
this.destroyPort();
},
messageListener: function (details) {
if (typeof details !== 'object' || details === null) {
return;
}
// Response to specific message previously sent
if (details.msgId !== undefined) {
const resolver = this.pending.get(details.msgId);
if (resolver !== undefined) {
this.pending.delete(details.msgId);
resolver(details.msg);
return;
}
}
},
messageListenerBound: null,
destroyPort: function () {
const port = this.port;
if (port !== null) {
port.disconnect();
port.onMessage.removeListener(this.messageListenerBound);
this.port = null;
}
// service pending callbacks
if (this.pending.size !== 0) {
const pending = this.pending;
this.pending = new Map();
for (const resolver of pending.values()) {
resolver();
}
}
},
createPort: function () {
if (this.shuttingDown) {
return null;
}
if (this.messageListenerBound === null) {
this.messageListenerBound = this.messageListener.bind(this);
// this.disconnectListenerBound = this.disconnectListener.bind(this);
}
try {
this.port = webext.runtime.connect({ name: 'hermes' }) || null;
} catch (ex) {
this.port = null;
}
if (this.port === null) {
return null;
}
this.port.onMessage.addListener(this.messageListenerBound);
return this.port;
},
getPort: function () {
return this.port !== null ? this.port : this.createPort();
},
send: function (channel, msg) {
if (this.pending.size > 50) {
this.shutdown();
}
const port = this.getPort();
if (port === null) {
return Promise.resolve();
}
const msgId = this.msgIdGenerator++;
const promise = new Promise((resolve) => {
this.pending.set(msgId, resolve);
});
port.postMessage({ channel, msgId, msg });
return promise;
}
};