@nerimity/nerimity.js 1.8.1 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,85 @@
1
+ import EventEmitter from "eventemitter3";
2
+ import { WebSocket } from "ws";
3
+
4
+ export type EventMap = {
5
+ ready: () => void;
6
+ };
7
+
8
+ const PORT_RANGES = [6463, 6472];
9
+
10
+ export interface EmitPayload {
11
+ name: string;
12
+ action?: string;
13
+ title?: string;
14
+ subtitle?: string;
15
+ imgSrc?: string;
16
+ startedAt?: number;
17
+ endsAt?: number;
18
+ speed?: number;
19
+ }
20
+ function findRunningServer(appId: string) {
21
+ return new Promise<null | WebSocket>((res) => {
22
+ let servers: WebSocket[] = [];
23
+ let id = setTimeout(() => {
24
+ res(null);
25
+ }, 5000);
26
+ for (let port = PORT_RANGES[0]; port < PORT_RANGES[1] + 1; port++) {
27
+ const server = new WebSocket(`ws://localhost:${port}?appId=${appId}`);
28
+ const index = servers.length;
29
+ servers.push(server);
30
+
31
+ server.on("message", (data) => {
32
+ const message = jsonParseCatch(data.toString());
33
+ if (message.name === "HELLO_NERIMITY_RPC") {
34
+ clearTimeout(id);
35
+ servers.forEach((server, i) => {
36
+ if (i === index) return;
37
+ server.removeAllListeners();
38
+ server.close();
39
+ });
40
+ server.send(JSON.stringify(message));
41
+ res(server);
42
+ }
43
+ });
44
+
45
+ server.on("error", (err) => {});
46
+ }
47
+ });
48
+ }
49
+
50
+ export class RPCClient extends EventEmitter<EventMap> {
51
+ appId?: string;
52
+ ws?: WebSocket | null;
53
+ loggedIn = false;
54
+ constructor() {
55
+ super();
56
+ }
57
+
58
+ send(payload: EmitPayload | null) {
59
+ if (!this.ws) return;
60
+ this.ws.send(
61
+ JSON.stringify({
62
+ name: "UPDATE_RPC",
63
+ data: payload,
64
+ })
65
+ );
66
+ }
67
+
68
+ async login(appId: string): Promise<boolean> {
69
+ if (this.loggedIn) return true;
70
+ this.appId = appId;
71
+ this.ws = await findRunningServer(appId);
72
+ if (!this.ws) return await this.login(appId);
73
+ this.loggedIn = true;
74
+ this.emit("ready");
75
+ return true;
76
+ }
77
+ }
78
+
79
+ const jsonParseCatch = (json: string) => {
80
+ try {
81
+ return JSON.parse(json);
82
+ } catch (e) {
83
+ return null;
84
+ }
85
+ };
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
- export { Client, Events } from './Client';
1
+ export { Client, Events } from "./Client";
2
2
 
3
+ export { RPCClient, EmitPayload } from "./RPCClient";