koishi-plugin-prism 0.2.0 → 0.3.0

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,349 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HaWatcher = exports.HA_TIMING = void 0;
4
+ exports.applyEvent = applyEvent;
5
+ exports.statesFrame = statesFrame;
6
+ exports.statusFrame = statusFrame;
7
+ exports.websocketUrl = websocketUrl;
8
+ exports.attemptOrder = attemptOrder;
9
+ exports.parseWatch = parseWatch;
10
+ exports.HA_TIMING = {
11
+ connectMs: 10_000,
12
+ authMs: 10_000,
13
+ heartbeatMs: 30_000,
14
+ firstRetryMs: 2_000,
15
+ maxRetryMs: 60_000,
16
+ };
17
+ const SUBSCRIPTION_ID = 1;
18
+ /** The attributes the platform uses; Home Assistant reports many more and forwarding them is only traffic. */
19
+ const KEPT_ATTRIBUTES = [
20
+ "hvac_modes",
21
+ "fan_modes",
22
+ "min_temp",
23
+ "max_temp",
24
+ "target_temp_step",
25
+ "temperature",
26
+ "current_temperature",
27
+ "fan_mode",
28
+ ];
29
+ const isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
30
+ const seconds = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
31
+ const stable = (value) => JSON.stringify(value, (_key, item) => isRecord(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
32
+ /**
33
+ * Two states are the same when what is reported is the same. `lastUpdated` moves with attributes that
34
+ * are never reported, so it must not make an otherwise identical state look changed.
35
+ */
36
+ const same = (a, b) => a.state === b.state && a.lastChanged === b.lastChanged && stable(a.attributes) === stable(b.attributes);
37
+ function kept(attributes) {
38
+ if (!isRecord(attributes))
39
+ return {};
40
+ return Object.fromEntries(Object.entries(attributes).filter(([name]) => KEPT_ATTRIBUTES.includes(name)));
41
+ }
42
+ /**
43
+ * Apply one `subscribe_entities` event (`a` added, `c` changed, `r` removed) and return the entities
44
+ * whose reported fields changed.
45
+ */
46
+ function applyEvent(states, event) {
47
+ const changed = [];
48
+ const put = (id, next) => {
49
+ const current = states.get(id);
50
+ if (current && same(current, next))
51
+ return;
52
+ states.set(id, next);
53
+ changed.push(id);
54
+ };
55
+ if (!isRecord(event))
56
+ return changed;
57
+ if (isRecord(event.a)) {
58
+ for (const [id, compressed] of Object.entries(event.a)) {
59
+ if (!isRecord(compressed))
60
+ continue;
61
+ put(id, {
62
+ state: typeof compressed.s === "string" ? compressed.s : "unknown",
63
+ attributes: kept(compressed.a),
64
+ lastChanged: seconds(compressed.lc),
65
+ lastUpdated: seconds(compressed.lu),
66
+ });
67
+ }
68
+ }
69
+ if (isRecord(event.c)) {
70
+ for (const [id, diff] of Object.entries(event.c)) {
71
+ if (!isRecord(diff))
72
+ continue;
73
+ const base = states.get(id);
74
+ const next = base
75
+ ? { ...base, attributes: { ...base.attributes } }
76
+ : { state: "", attributes: {}, lastChanged: null, lastUpdated: null };
77
+ if (isRecord(diff["+"])) {
78
+ const plus = diff["+"];
79
+ if (typeof plus.s === "string")
80
+ next.state = plus.s;
81
+ Object.assign(next.attributes, kept(plus.a));
82
+ if (seconds(plus.lc) !== null)
83
+ next.lastChanged = seconds(plus.lc);
84
+ if (seconds(plus.lu) !== null)
85
+ next.lastUpdated = seconds(plus.lu);
86
+ }
87
+ const minus = isRecord(diff["-"]) ? diff["-"].a : undefined;
88
+ if (Array.isArray(minus))
89
+ for (const name of minus)
90
+ if (typeof name === "string")
91
+ delete next.attributes[name];
92
+ put(id, next);
93
+ }
94
+ }
95
+ if (Array.isArray(event.r))
96
+ for (const id of event.r)
97
+ if (typeof id === "string")
98
+ states.delete(id);
99
+ return changed;
100
+ }
101
+ function statesFrame(term, connection, full, states, ids) {
102
+ return {
103
+ type: "ha",
104
+ method: "ha.states",
105
+ params: {
106
+ term,
107
+ connection,
108
+ full,
109
+ states: ids.flatMap((id) => {
110
+ const state = states.get(id);
111
+ return state
112
+ ? [{ entity_id: id, state: state.state, last_changed: state.lastChanged, last_updated: state.lastUpdated, attributes: state.attributes }]
113
+ : [];
114
+ }),
115
+ },
116
+ };
117
+ }
118
+ function statusFrame(term, connection, connected, error) {
119
+ return { type: "ha", method: "ha.status", params: { term, connection, connected, error } };
120
+ }
121
+ /** `http(s)://host[:port]` to the WebSocket API address; null for anything else. */
122
+ function websocketUrl(base) {
123
+ const trimmed = base.trim().replace(/\/+$/, "");
124
+ const match = /^(https?):\/\/(.+)$/i.exec(trimmed);
125
+ if (!match)
126
+ return null;
127
+ return `${match[1].toLowerCase() === "https" ? "wss" : "ws"}://${match[2]}/api/websocket`;
128
+ }
129
+ /** The addresses in the order to try them: rotated to start at the one that worked last. */
130
+ function attemptOrder(length, lastGood) {
131
+ return Array.from({ length }, (_, step) => (lastGood + step) % length);
132
+ }
133
+ /** An `ha.watch` body, or null when it is not one (the platform then has nothing for this bot to watch). */
134
+ function parseWatch(value) {
135
+ if (!isRecord(value) || typeof value.term !== "number" || !Array.isArray(value.connections))
136
+ return null;
137
+ const connections = [];
138
+ for (const item of value.connections) {
139
+ if (!isRecord(item) || typeof item.id !== "string" || typeof item.token !== "string")
140
+ return null;
141
+ if (!Array.isArray(item.urls) || !item.urls.every((url) => typeof url === "string"))
142
+ return null;
143
+ if (!Array.isArray(item.entities) || !item.entities.every((entity) => typeof entity === "string"))
144
+ return null;
145
+ connections.push({ id: item.id, urls: item.urls, token: item.token, entities: item.entities });
146
+ }
147
+ return { term: value.term, connections };
148
+ }
149
+ const reason = (error) => (error instanceof Error ? error.message : typeof error === "string" ? error : "connection error");
150
+ class HaWatcher {
151
+ open;
152
+ send;
153
+ logger;
154
+ timing;
155
+ /** Bumped whenever the watch is replaced or stopped, so a run that was left behind knows to end. */
156
+ generation = 0;
157
+ aborts = new Set();
158
+ waits = new Set();
159
+ constructor(open, send, logger, timing = exports.HA_TIMING) {
160
+ this.open = open;
161
+ this.send = send;
162
+ this.logger = logger;
163
+ this.timing = timing;
164
+ }
165
+ /** Watch what the platform asked for, in place of whatever was watched before. */
166
+ watch(watch) {
167
+ this.stop();
168
+ const generation = this.generation;
169
+ for (const connection of watch.connections)
170
+ void this.run(generation, watch.term, connection);
171
+ }
172
+ /** Stop watching, and drop every Home Assistant connection. */
173
+ stop() {
174
+ this.generation += 1;
175
+ for (const abort of [...this.aborts])
176
+ abort();
177
+ this.aborts.clear();
178
+ for (const wait of [...this.waits]) {
179
+ clearTimeout(wait.timer);
180
+ wait.done();
181
+ }
182
+ this.waits.clear();
183
+ }
184
+ current(generation) {
185
+ return generation === this.generation;
186
+ }
187
+ report(generation, frame) {
188
+ if (!this.current(generation))
189
+ return;
190
+ try {
191
+ this.send(frame);
192
+ }
193
+ catch (error) {
194
+ this.logger?.warn("PRiSM Home Assistant report failed", error);
195
+ }
196
+ }
197
+ wait(ms) {
198
+ return new Promise((resolve) => {
199
+ const entry = { timer: setTimeout(() => finish(), ms), done: () => finish() };
200
+ const finish = () => {
201
+ this.waits.delete(entry);
202
+ resolve();
203
+ };
204
+ this.waits.add(entry);
205
+ });
206
+ }
207
+ async run(generation, term, connection) {
208
+ let delay = this.timing.firstRetryMs;
209
+ let first = 0;
210
+ while (this.current(generation)) {
211
+ const failures = [];
212
+ for (const index of attemptOrder(connection.urls.length, first)) {
213
+ if (!this.current(generation))
214
+ return;
215
+ const url = connection.urls[index];
216
+ const outcome = await this.watchOnce(generation, term, connection, url);
217
+ if (!this.current(generation))
218
+ return;
219
+ if (outcome.up) {
220
+ // It was up and then ended; start over from it, and without a long wait.
221
+ first = index;
222
+ delay = this.timing.firstRetryMs;
223
+ failures.length = 0;
224
+ if (outcome.error) {
225
+ this.logger?.warn(`Home Assistant ${url}: ${outcome.error}`);
226
+ this.report(generation, statusFrame(term, connection.id, false, outcome.error));
227
+ }
228
+ break;
229
+ }
230
+ const error = outcome.error ?? "closed before signing in";
231
+ this.logger?.warn(`Home Assistant ${url}: ${error}`);
232
+ failures.push(`${url}: ${error}`);
233
+ }
234
+ if (failures.length)
235
+ this.report(generation, statusFrame(term, connection.id, false, failures.join("; ")));
236
+ await this.wait(delay);
237
+ delay = Math.min(delay * 2, this.timing.maxRetryMs);
238
+ }
239
+ }
240
+ /** One attempt at one address, ending when the connection does. `up` says it got as far as subscribing. */
241
+ watchOnce(generation, term, connection, base) {
242
+ return new Promise((resolve) => {
243
+ const url = websocketUrl(base);
244
+ if (!url)
245
+ return resolve({ up: false, error: `unsupported address ${base}` });
246
+ let socket;
247
+ try {
248
+ socket = this.open(url, {});
249
+ }
250
+ catch (error) {
251
+ return resolve({ up: false, error: reason(error) });
252
+ }
253
+ const states = new Map();
254
+ let up = false;
255
+ let settled = false;
256
+ let awaitingPong = false;
257
+ let firstEvent = true;
258
+ let nextId = SUBSCRIPTION_ID + 1;
259
+ let authTimer;
260
+ let beat;
261
+ const abort = () => finish(null);
262
+ const finish = (error) => {
263
+ if (settled)
264
+ return;
265
+ settled = true;
266
+ clearTimeout(connectTimer);
267
+ clearTimeout(authTimer);
268
+ clearInterval(beat);
269
+ this.aborts.delete(abort);
270
+ try {
271
+ socket.close(1000, "done");
272
+ }
273
+ catch {
274
+ // Already closed.
275
+ }
276
+ resolve({ up, error });
277
+ };
278
+ this.aborts.add(abort);
279
+ const connectTimer = setTimeout(() => finish("connecting timed out"), this.timing.connectMs);
280
+ socket.addEventListener("open", () => {
281
+ if (settled)
282
+ return;
283
+ clearTimeout(connectTimer);
284
+ authTimer = setTimeout(() => finish("signing in timed out"), this.timing.authMs);
285
+ });
286
+ socket.addEventListener("error", (event) => finish(reason(event?.error ?? event?.message ?? event)));
287
+ socket.addEventListener("close", () => finish(up ? null : "closed before signing in"));
288
+ socket.addEventListener("message", (event) => {
289
+ if (settled)
290
+ return;
291
+ let message;
292
+ try {
293
+ const parsed = JSON.parse(String(event?.data ?? ""));
294
+ if (!isRecord(parsed))
295
+ return;
296
+ message = parsed;
297
+ }
298
+ catch {
299
+ return;
300
+ }
301
+ switch (message.type) {
302
+ case "auth_required":
303
+ socket.send(JSON.stringify({ type: "auth", access_token: connection.token }));
304
+ break;
305
+ case "auth_invalid":
306
+ finish("Home Assistant rejected the token");
307
+ break;
308
+ case "auth_ok":
309
+ clearTimeout(authTimer);
310
+ socket.send(JSON.stringify({ id: SUBSCRIPTION_ID, type: "subscribe_entities", entity_ids: connection.entities }));
311
+ up = true;
312
+ this.report(generation, statusFrame(term, connection.id, true, null));
313
+ beat = setInterval(() => {
314
+ if (awaitingPong)
315
+ return finish("Home Assistant stopped answering");
316
+ awaitingPong = true;
317
+ socket.send(JSON.stringify({ id: nextId++, type: "ping" }));
318
+ this.report(generation, statusFrame(term, connection.id, true, null));
319
+ }, this.timing.heartbeatMs);
320
+ break;
321
+ case "event":
322
+ if (message.id !== SUBSCRIPTION_ID)
323
+ break;
324
+ {
325
+ const changed = applyEvent(states, message.event);
326
+ if (firstEvent) {
327
+ // The first event is everything that exists now.
328
+ this.report(generation, statesFrame(term, connection.id, true, states, [...states.keys()]));
329
+ firstEvent = false;
330
+ }
331
+ else if (changed.length) {
332
+ this.report(generation, statesFrame(term, connection.id, false, states, changed));
333
+ }
334
+ }
335
+ break;
336
+ case "result":
337
+ if (message.id === SUBSCRIPTION_ID && message.success === false) {
338
+ finish(isRecord(message.error) && typeof message.error.message === "string" ? message.error.message : "subscription refused");
339
+ }
340
+ break;
341
+ case "pong":
342
+ awaitingPong = false;
343
+ break;
344
+ }
345
+ });
346
+ });
347
+ }
348
+ }
349
+ exports.HaWatcher = HaWatcher;
package/lib/index.d.ts CHANGED
@@ -1,4 +1,7 @@
1
+ import { type HaWatch } from "./ha-watch.js";
1
2
  import { Schema } from "koishi";
3
+ export { HaWatcher } from "./ha-watch.js";
4
+ export type { HaWatch } from "./ha-watch.js";
2
5
  export declare const name = "prism";
3
6
  export declare const version: string;
4
7
  export declare const Config: Schema<PrismKoishiPluginConfig>;
@@ -10,33 +13,49 @@ export declare class PrismBotClientError extends Error {
10
13
  readonly originalError?: unknown | undefined;
11
14
  constructor(message: string, code: string, status: number, body: unknown, originalError?: unknown | undefined);
12
15
  }
13
- export type MahjongTableConfig = {
14
- tableId: string;
15
- displayName: string;
16
- aliases: string[];
17
- pricingConfigIds: string[];
16
+ /** What the bot is told about itself and the shop by `GET integration/bot`. */
17
+ export type BotConfig = {
18
+ bot: {
19
+ id: string;
20
+ name: string;
21
+ };
22
+ settings: {
23
+ /** "readonly" leaves players binding, lookups and redeeming; staff keep every command. */
24
+ playerCommands: "all" | "readonly";
25
+ readOnlyNotice: string;
26
+ /** Staff may act for other players. */
27
+ staffCommands: boolean;
28
+ /** Only staff may switch machines off. */
29
+ powerOffStaffOnly: boolean;
30
+ /** Staff on the same platform get checkout receipts privately. */
31
+ receiptsToStaff: boolean;
32
+ /** Channels (`platform:channelId`) told before an idle power-off. */
33
+ idleChannelIds: string[];
34
+ /** How many minutes before an idle power-off to tell them; 0 for never. */
35
+ idleReminderMinutes: number;
36
+ /** Whether this bot offers to watch the shop's Home Assistant. */
37
+ watchHomeAssistant: boolean;
38
+ };
39
+ billingEnabled: boolean;
40
+ currencyName: string;
41
+ /** Staff are these platform identities. */
42
+ staff: Array<{
43
+ provider: string;
44
+ subject: string;
45
+ }>;
46
+ /** The door `lock`/开门 opens. */
47
+ door: {
48
+ id: string;
49
+ name: string;
50
+ } | null;
51
+ mahjongTables: Array<{
52
+ id: string;
53
+ name: string;
54
+ aliases: string[];
55
+ capacity: number;
56
+ }>;
18
57
  };
19
- export type MahjongTableConfigInput = Omit<MahjongTableConfig, "tableId">;
20
58
  export type PrismKoishiPluginConfig = {
21
- autoRegister: boolean;
22
- /** "readonly" leaves players binding, lookups and redeeming; staff keep every command. */
23
- playerCommands?: "all" | "readonly";
24
- readOnlyNotice?: string;
25
- loginPricingConfigIds?: string[];
26
- loginSessionLabel?: string;
27
- defaultDoorDeviceId: string;
28
- defaultScanProvider: string;
29
- currencyName: string;
30
- enableStaffCommands?: boolean;
31
- staffUserIds?: string[];
32
- powerCommandsAdminOnly?: boolean;
33
- logoutNotifyUserIds?: string[];
34
- mahjongTableConfigs?: MahjongTableConfigInput[];
35
- mahjongTableSize?: number;
36
- /** Channels (`platform:channelId`) told before an idle power-off. */
37
- idleNotifyChannelIds?: string[];
38
- /** How many minutes before an idle power-off to tell them; 0 for never. */
39
- idleReminderMinutes?: number;
40
59
  /**
41
60
  * Used by /list to resolve player display names from the chat platform.
42
61
  * For Koishi, this maps an adapter subject and provider to a nickname (e.g. the
@@ -54,6 +73,8 @@ export type PrismKoishiPluginConfig = {
54
73
  socket?: SocketFactory;
55
74
  /** Plain HTTP POST, used only by `api测速`; defaults to Koishi's `ctx.http`. Mainly for tests. */
56
75
  httpPost?: HttpPost;
76
+ /** Opens connections to Home Assistant; defaults to Koishi's `ctx.http.ws`. Mainly for tests. */
77
+ haSocket?: SocketFactory;
57
78
  };
58
79
  /** A plain HTTP POST answering with its status, headers and decoded body. */
59
80
  export type HttpPost = (url: string, headers: Record<string, string>, body: unknown) => Promise<{
@@ -124,9 +145,19 @@ export declare class PrismSocket {
124
145
  private readonly open;
125
146
  private readonly url;
126
147
  private readonly token;
148
+ /**
149
+ * What to say in hello, read afresh each time: the bot's settings live on
150
+ * the platform, so they are fetched over this connection before it is
151
+ * sent. Null when they could not be read.
152
+ */
127
153
  private readonly hello;
128
154
  private readonly onEvent;
129
155
  private readonly logger?;
156
+ /**
157
+ * `onWatch`: the platform asked this bot to watch Home Assistant, or with null to stop.
158
+ * `onClose`: the connection is gone, and with it the platform's idea of what this bot watches.
159
+ */
160
+ private readonly hooks?;
130
161
  private socket;
131
162
  private readonly pending;
132
163
  private retryMs;
@@ -135,13 +166,38 @@ export declare class PrismSocket {
135
166
  private lastHeard;
136
167
  private stopped;
137
168
  private sequence;
169
+ /** Bumped by every hello being prepared, so only the newest one is sent. */
170
+ private greeting;
138
171
  private readonly pongWaiters;
139
- constructor(open: SocketFactory, url: string, token: string, hello: Record<string, unknown>, onEvent: (event: PlatformEvent) => void, logger?: {
172
+ constructor(open: SocketFactory, url: string, token: string,
173
+ /**
174
+ * What to say in hello, read afresh each time: the bot's settings live on
175
+ * the platform, so they are fetched over this connection before it is
176
+ * sent. Null when they could not be read.
177
+ */
178
+ hello: () => Promise<Record<string, unknown> | null>, onEvent: (event: PlatformEvent) => void, logger?: {
140
179
  warn(...args: unknown[]): void;
180
+ } | undefined,
181
+ /**
182
+ * `onWatch`: the platform asked this bot to watch Home Assistant, or with null to stop.
183
+ * `onClose`: the connection is gone, and with it the platform's idea of what this bot watches.
184
+ */
185
+ hooks?: {
186
+ onWatch(watch: HaWatch | null): void;
187
+ onClose(): void;
141
188
  } | undefined);
189
+ /** Send a frame if the connection is up; a report made while it is down is dropped, as the platform has forgotten the watch by then. */
190
+ send(frame: Record<string, unknown>): void;
142
191
  start(): void;
143
192
  stop(): void;
144
193
  private connect;
194
+ /**
195
+ * Read the bot's settings and say hello with them: on connecting, and again
196
+ * when the platform says they changed. A connection that cannot read them
197
+ * at all is closed and tried again later, without resetting the backoff, so
198
+ * a platform that keeps failing is not asked every second.
199
+ */
200
+ private greet;
145
201
  private reconnectLater;
146
202
  private failPending;
147
203
  private receive;
@@ -167,7 +223,6 @@ export type Sender = {
167
223
  provider: string;
168
224
  };
169
225
  export declare function humanReadableBotError(error: PrismBotClientError): string;
170
- export declare function resolveMahjongTableConfigs(structured: readonly MahjongTableConfigInput[]): Map<string, MahjongTableConfig>;
171
226
  declare const _default: {
172
227
  name: string;
173
228
  Config: Schema<PrismKoishiPluginConfig>;