40 lines
952 B
JavaScript
40 lines
952 B
JavaScript
// 事件枢纽:插件运行线程产生的 日志/进度/完成 事件 → WS 广播给渲染层。
|
|
// 对齐 Python webhost hub.py 语义(t/run_id/plugin_id/level/pct/ok/error)。
|
|
"use strict";
|
|
|
|
const { EventEmitter } = require("events");
|
|
|
|
class Hub extends EventEmitter {
|
|
constructor() {
|
|
super();
|
|
this._clients = new Set(); // ws 连接
|
|
}
|
|
|
|
// 由 server.js 在 WS 连接建立后注册
|
|
addClient(ws) {
|
|
this._clients.add(ws);
|
|
ws.on("close", () => this._clients.delete(ws));
|
|
ws.on("error", () => this._clients.delete(ws));
|
|
}
|
|
|
|
clientCount() {
|
|
return this._clients.size;
|
|
}
|
|
|
|
publish(event) {
|
|
this.emit("event", event);
|
|
const payload = JSON.stringify(event);
|
|
for (const ws of this._clients) {
|
|
try {
|
|
if (ws.readyState === 1 /* OPEN */) ws.send(payload);
|
|
} catch (e) {
|
|
this._clients.delete(ws);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const HUB = new Hub();
|
|
|
|
module.exports = { Hub, HUB };
|