indigo-matter-bridge 0.5.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.
package/dist/window.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * The enhanced-commissioning-window state machine (§3.8).
3
+ *
4
+ * Extracted from {@link BridgeNode} so the bookkeeping — double-open refusal,
5
+ * expiry, and which reason a `window_closed` event carries — is unit-testable
6
+ * without a Matter stack. Timer and clock are injected for the same reason.
7
+ */
8
+ import { describeError, ErrorCode, ProtocolError } from "./protocol.js";
9
+ /** Real timers, unref'd: an open window must never keep the process alive. */
10
+ export const defaultScheduler = (callback, ms) => {
11
+ const timer = setTimeout(callback, ms);
12
+ timer.unref?.();
13
+ return () => clearTimeout(timer);
14
+ };
15
+ export class CommissioningWindow {
16
+ #open;
17
+ #cancel;
18
+ #listener;
19
+ #schedule;
20
+ #now;
21
+ #log;
22
+ #onExpire;
23
+ constructor(options = {}) {
24
+ this.#schedule = options.schedule ?? defaultScheduler;
25
+ this.#now = options.now ?? Date.now;
26
+ this.#log = options.log ?? (() => { });
27
+ this.#onExpire = options.onExpire;
28
+ }
29
+ /** Register the `window_closed` sink (§5). Last registration wins. */
30
+ onClosed(listener) {
31
+ this.#listener = listener;
32
+ }
33
+ get isOpen() {
34
+ return this.#open !== undefined;
35
+ }
36
+ /** The live window, or `undefined` when none is open. */
37
+ get current() {
38
+ return this.#open;
39
+ }
40
+ /**
41
+ * Refuse a second window *before* anything Matter-side is touched.
42
+ *
43
+ * matter.js 0.17.8's `DeviceCommissioner.allowEnhancedCommissioning` installs
44
+ * the new PASE commissioner and only then throws on the double-open, so a
45
+ * refusal that reaches the stack has already invalidated the code the user
46
+ * is holding. Guarding here keeps the open window intact.
47
+ */
48
+ assertClosed() {
49
+ if (this.#open !== undefined) {
50
+ throw new ProtocolError(ErrorCode.commissioningWindowFailed, "A commissioning window is already open");
51
+ }
52
+ }
53
+ /** Record a freshly opened window and arm its expiry. */
54
+ open(durationSeconds, manualPairingCode, qrPairingCode) {
55
+ this.assertClosed();
56
+ const expiresAt = new Date(this.#now() + durationSeconds * 1000);
57
+ this.#open = { expiresAt, manualPairingCode, qrPairingCode };
58
+ this.#cancel = this.#schedule(() => this.#expire(), durationSeconds * 1000);
59
+ return expiresAt;
60
+ }
61
+ /**
62
+ * matter.js reports its window ended. Returns `false` when we had already
63
+ * closed ours — which is what keeps expiry from announcing twice, since the
64
+ * expiry path itself calls `endCommissioning()` and that fires this back.
65
+ */
66
+ noteEnded() {
67
+ if (this.#open === undefined) {
68
+ return false;
69
+ }
70
+ this.#discard();
71
+ this.#log("Commissioning window closed by commissioner");
72
+ this.#emit("commissioned");
73
+ return true;
74
+ }
75
+ /** Shutdown: drop the window without announcing a close. */
76
+ clear() {
77
+ this.#discard();
78
+ }
79
+ #expire() {
80
+ if (this.#open === undefined) {
81
+ return;
82
+ }
83
+ this.#discard();
84
+ this.#log("Commissioning window expired");
85
+ this.#emit("expired");
86
+ try {
87
+ this.#onExpire?.();
88
+ }
89
+ catch (error) {
90
+ this.#log(`Failed to end Matter commissioning after expiry: ${describeError(error)}`);
91
+ }
92
+ }
93
+ #discard() {
94
+ this.#cancel?.();
95
+ this.#cancel = undefined;
96
+ this.#open = undefined;
97
+ }
98
+ #emit(reason) {
99
+ try {
100
+ this.#listener?.(reason);
101
+ }
102
+ catch (error) {
103
+ this.#log(`window_closed(${reason}) listener failed: ${describeError(error)}`);
104
+ }
105
+ }
106
+ }
107
+ //# sourceMappingURL=window.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"window.js","sourceRoot":"","sources":["../src/window.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,aAAa,EAA2B,MAAM,eAAe,CAAC;AAQjG,8EAA8E;AAC9E,MAAM,CAAC,MAAM,gBAAgB,GAAc,CAAC,QAAQ,EAAE,EAAE,EAAE,EAAE;IACxD,MAAM,KAAK,GAAG,UA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G,SAAS,CAAC;IAC3B,CAAC;IAED,KAAK,CAAC,MAA0B;QAC5B,IAAI,CAAC;YACD,IAAI,CAAC,SAAS,EAAE,CAAC,MAAM,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,CAAC,IAAI,CAAC,iBAAiB,MAAM,sBAAsB,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnF,CAAC;IACL,CAAC;CACJ"}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The plugin ⇄ bridge-node WebSocket server (BRIDGE_PROTOCOL.md).
3
+ *
4
+ * Loopback only: there is no auth on this socket because there is no remote
5
+ * surface (§6.1). No matter.js import here — the server talks to a
6
+ * {@link BridgeFacade}, which is what makes the protocol testable without a
7
+ * live Matter stack.
8
+ */
9
+ import { type BridgeFacade, type EventNameValue } from "./protocol.js";
10
+ export declare const LOOPBACK_HOST = "127.0.0.1";
11
+ export interface BridgeWsServerOptions {
12
+ port: number;
13
+ bridge: BridgeFacade;
14
+ bridgeVersion: string;
15
+ matterJsVersion: string;
16
+ log?: (message: string) => void;
17
+ /** Overridable so the §2 timeout is testable without a 10s wait. */
18
+ unattachedTimeoutMs?: number;
19
+ }
20
+ export declare class BridgeWsServer {
21
+ #private;
22
+ private readonly options;
23
+ constructor(options: BridgeWsServerOptions);
24
+ /**
25
+ * Push an unsolicited event (§1/§5) to the attached client.
26
+ *
27
+ * Dropped when nobody is attached — the plugin re-`attach`es on reconnect
28
+ * and gets a full reconcile, so a missed event has nothing to recover — but
29
+ * never dropped *silently*: a run of these is how "I pressed the switch in
30
+ * Apple Home and Indigo did nothing" looks from the node's side, and
31
+ * without the line there is no way to tell it from a broken listener.
32
+ */
33
+ sendEvent(event: EventNameValue, data: Record<string, unknown>): void;
34
+ /** Bind and start accepting connections. Resolves once listening. */
35
+ listen(): Promise<void>;
36
+ /** The bound port — useful when a test asks for port 0. */
37
+ get port(): number;
38
+ close(): Promise<void>;
39
+ private onConnection;
40
+ private onMessage;
41
+ private handleAttach;
42
+ private handleSetState;
43
+ private handleSetReachable;
44
+ private handleOpenWindow;
45
+ private sendError;
46
+ /**
47
+ * Write one frame, reporting whether it went.
48
+ *
49
+ * Never throws: a serialisation failure here would otherwise escape into
50
+ * whatever was mid-flight (an observable, a handler chain) rather than into
51
+ * the response the caller is trying to send.
52
+ */
53
+ private send;
54
+ }
@@ -0,0 +1,349 @@
1
+ /**
2
+ * The plugin ⇄ bridge-node WebSocket server (BRIDGE_PROTOCOL.md).
3
+ *
4
+ * Loopback only: there is no auth on this socket because there is no remote
5
+ * surface (§6.1). No matter.js import here — the server talks to a
6
+ * {@link BridgeFacade}, which is what makes the protocol testable without a
7
+ * live Matter stack.
8
+ */
9
+ import { WebSocketServer } from "ws";
10
+ import { describeError, describeErrorWithStack, endpointMapInvalidDetails, ErrorCode, EventName, PROTOCOL_VERSION, ProtocolError, RECOVERY_COMMANDS, UNATTACHED_TIMEOUT_MS, WINDOW_DURATION_DEFAULT_SECONDS, WINDOW_DURATION_MAX_SECONDS, WINDOW_DURATION_MIN_SECONDS, } from "./protocol.js";
11
+ import { parseDeviceId, parseEndpointSpec, parseEndpointSpecs, parseFabricIndex, parsePreserveEndpointNumbers, parseReplaceAll, } from "./reconcile.js";
12
+ export const LOOPBACK_HOST = "127.0.0.1";
13
+ export class BridgeWsServer {
14
+ options;
15
+ #wss;
16
+ #attached;
17
+ #clients = new Map();
18
+ #handlers = new Map();
19
+ #log;
20
+ constructor(options) {
21
+ this.options = options;
22
+ this.#log = options.log ?? console.log;
23
+ this.#handlers.set("attach", (args, socket, state) => this.handleAttach(args, socket, state));
24
+ this.#handlers.set("get_status", async () => this.options.bridge.getStatus());
25
+ this.#handlers.set("get_pairing", async () => this.options.bridge.getPairing());
26
+ this.#handlers.set("open_commissioning_window", async (args) => this.handleOpenWindow(args));
27
+ this.#handlers.set("upsert_endpoint", async (args) => this.options.bridge.upsertEndpoint(parseEndpointSpec(args.endpoint)));
28
+ this.#handlers.set("remove_endpoint", async (args) => this.options.bridge.removeEndpoint(parseDeviceId(args.indigoDeviceId)));
29
+ this.#handlers.set("set_state", async (args) => this.handleSetState(args));
30
+ this.#handlers.set("set_reachable", async (args) => this.handleSetReachable(args));
31
+ // Returns the node's own outcome rather than a blanket `{}`: the plugin
32
+ // reports this removal to the user in the past tense, and "there was no
33
+ // fabric at that index" has to be able to reach it (§3.9).
34
+ this.#handlers.set("remove_fabric", async (args) => this.options.bridge.removeFabric(parseFabricIndex(args.fabricIndex)));
35
+ this.#handlers.set("factory_reset", async (args) => {
36
+ await this.options.bridge.factoryReset(parsePreserveEndpointNumbers(args.preserveEndpointNumbers));
37
+ return {};
38
+ });
39
+ this.#handlers.set("rebuild_endpoint_map", async () => this.options.bridge.rebuildEndpointMap());
40
+ options.bridge.onWindowClosed(reason => this.sendEvent(EventName.windowClosed, { reason }));
41
+ options.bridge.onCommand(data => this.sendEvent(EventName.command, data));
42
+ options.bridge.onDriftDetected(drift => this.sendEvent(EventName.driftDetected, { drift }));
43
+ options.bridge.onFabricsChanged((fabrics, change) => this.sendEvent(EventName.fabricsChanged, { fabrics, change }));
44
+ options.bridge.onCommissioned(() => this.sendEvent(EventName.commissioned, {}));
45
+ options.bridge.onDecommissioned(() => this.sendEvent(EventName.decommissioned, {}));
46
+ }
47
+ /**
48
+ * Push an unsolicited event (§1/§5) to the attached client.
49
+ *
50
+ * Dropped when nobody is attached — the plugin re-`attach`es on reconnect
51
+ * and gets a full reconcile, so a missed event has nothing to recover — but
52
+ * never dropped *silently*: a run of these is how "I pressed the switch in
53
+ * Apple Home and Indigo did nothing" looks from the node's side, and
54
+ * without the line there is no way to tell it from a broken listener.
55
+ */
56
+ sendEvent(event, data) {
57
+ const socket = this.#attached;
58
+ if (socket === undefined) {
59
+ const device = typeof data.indigoDeviceId === "number" ? ` for device ${data.indigoDeviceId}` : "";
60
+ this.#log(`Dropping ${event} event${device}: no client is attached`);
61
+ return;
62
+ }
63
+ const frame = { event, data };
64
+ this.send(socket, frame);
65
+ }
66
+ /** Bind and start accepting connections. Resolves once listening. */
67
+ async listen() {
68
+ await new Promise((resolve, reject) => {
69
+ const wss = new WebSocketServer({ host: LOOPBACK_HOST, port: this.options.port });
70
+ wss.once("error", reject);
71
+ wss.once("listening", () => {
72
+ wss.off("error", reject);
73
+ wss.on("error", error => this.#log(`WebSocket server error: ${describeError(error)}`));
74
+ resolve();
75
+ });
76
+ wss.on("connection", socket => this.onConnection(socket));
77
+ this.#wss = wss;
78
+ });
79
+ this.#log(`Protocol WebSocket listening on ws://${LOOPBACK_HOST}:${this.options.port}`);
80
+ }
81
+ /** The bound port — useful when a test asks for port 0. */
82
+ get port() {
83
+ const address = this.#wss?.address();
84
+ if (address === undefined || address === null || typeof address === "string") {
85
+ return this.options.port;
86
+ }
87
+ return address.port;
88
+ }
89
+ async close() {
90
+ const wss = this.#wss;
91
+ this.#wss = undefined;
92
+ for (const [socket, state] of this.#clients) {
93
+ clearTimeout(state.unattachedTimer);
94
+ // `terminate`, not `close`: a graceful close waits for the peer's
95
+ // close frame, and shutdown must not be held hostage by a plugin
96
+ // that is itself mid-crash. `wss.close()` below then resolves.
97
+ socket.terminate();
98
+ }
99
+ this.#clients.clear();
100
+ this.#attached = undefined;
101
+ if (wss !== undefined) {
102
+ await new Promise(resolve => wss.close(() => resolve()));
103
+ }
104
+ }
105
+ onConnection(socket) {
106
+ const state = { attached: false, pending: Promise.resolve() };
107
+ this.#clients.set(socket, state);
108
+ // Before the handshake send: `ws` throws an unhandled 'error' event if a
109
+ // socket fails with no listener attached, and a socket can fail on the
110
+ // very first write.
111
+ socket.on("error", error => this.#log(`Socket error: ${describeError(error)}`));
112
+ // §2 step 1: the bare handshake frame, before anything else.
113
+ const handshake = {
114
+ protocolVersion: PROTOCOL_VERSION,
115
+ bridgeVersion: this.options.bridgeVersion,
116
+ matterJsVersion: this.options.matterJsVersion,
117
+ };
118
+ socket.send(JSON.stringify(handshake));
119
+ // §2: a connection that handshakes but never attaches is closed.
120
+ const timeoutMs = this.options.unattachedTimeoutMs ?? UNATTACHED_TIMEOUT_MS;
121
+ // Said once per socket, not once per period: while the node is refusing
122
+ // the plugin holds this connection open indefinitely, and a line every
123
+ // 10s for the life of the process buries everything else in the log.
124
+ let announcedHold = false;
125
+ const armUnattachedTimer = () => {
126
+ state.unattachedTimer = setTimeout(() => {
127
+ if (state.attached) {
128
+ return;
129
+ }
130
+ // Deferred, not disarmed, while we are refusing. In that state
131
+ // the node itself is what stops this client attaching (§1.1
132
+ // refuses `attach`), and the plugin deliberately HOLDS the
133
+ // socket open un-attached because it is the only route to the
134
+ // §3.11 rebuild. Closing it anyway put the two in a fight:
135
+ // refuse, close, reconnect, refuse — every 10s, and a rebuild
136
+ // the user had just confirmed could be cut off mid-flight by
137
+ // our own timer. Re-arming rather than returning bare is what
138
+ // keeps the check alive AFTER the rebuild clears the refusal:
139
+ // a one-shot timer had already fired by then, so a client that
140
+ // still never attached was never reaped again for the life of
141
+ // the process.
142
+ if (this.options.bridge.endpointMapRefusal() !== undefined) {
143
+ if (!announcedHold) {
144
+ announcedHold = true;
145
+ this.#log("Holding an un-attached connection open: the node is refusing to serve " +
146
+ "endpoints and this socket is the client's only route to " +
147
+ "rebuild_endpoint_map (§1.1)");
148
+ }
149
+ armUnattachedTimer();
150
+ return;
151
+ }
152
+ this.#log(`Closing connection that did not attach within ${timeoutMs}ms`);
153
+ socket.close();
154
+ }, timeoutMs);
155
+ state.unattachedTimer.unref?.();
156
+ };
157
+ armUnattachedTimer();
158
+ socket.on("message", (data, isBinary) => {
159
+ if (isBinary) {
160
+ // The protocol is JSON text frames only (§1); nothing to answer.
161
+ this.#log("Dropping binary frame");
162
+ return;
163
+ }
164
+ const raw = data.toString();
165
+ // §1: strictly in receipt order — chain, never fan out. The tail
166
+ // catch also guarantees the chain is never left rejected, so one bad
167
+ // frame cannot stall every frame behind it.
168
+ state.pending = state.pending
169
+ .then(() => this.onMessage(socket, state, raw))
170
+ .catch(error => this.#log(`Frame handling failed: ${describeErrorWithStack(error)}`));
171
+ });
172
+ socket.on("close", () => {
173
+ clearTimeout(state.unattachedTimer);
174
+ this.#clients.delete(socket);
175
+ if (this.#attached === socket) {
176
+ this.#attached = undefined;
177
+ this.#log("Attached client disconnected");
178
+ }
179
+ });
180
+ }
181
+ async onMessage(socket, state, raw) {
182
+ let frame;
183
+ try {
184
+ frame = JSON.parse(raw);
185
+ }
186
+ catch {
187
+ // Unaddressable: no message_id to echo, so there is nobody to answer.
188
+ this.#log("Dropping unparseable frame");
189
+ return;
190
+ }
191
+ if (typeof frame !== "object" || frame === null) {
192
+ this.#log("Dropping non-object frame");
193
+ return;
194
+ }
195
+ const { message_id: messageId, command, args } = frame;
196
+ if (typeof messageId !== "string") {
197
+ this.#log("Dropping frame without a message_id");
198
+ return;
199
+ }
200
+ if (typeof command !== "string") {
201
+ this.send(socket, { message_id: messageId, error_code: ErrorCode.malformedArgs, details: "Missing command" });
202
+ return;
203
+ }
204
+ const commandArgs = typeof args === "object" && args !== null ? args : {};
205
+ // The refuse-to-start gate comes before everything, including the
206
+ // attach gate. In this state there is nothing to attach *to* — the node
207
+ // will not create an endpoint until its map is rebuilt — so answering
208
+ // `not_attached` would send the plugin round a reconnect loop that can
209
+ // never succeed, and hide the one error that names the remedy. The
210
+ // three §1.1 recovery commands are exempt from the attach requirement
211
+ // for the same reason: the client holding this socket open never got to
212
+ // attach, and `rebuild_endpoint_map` is the only way it ever will.
213
+ const refusal = this.options.bridge.endpointMapRefusal();
214
+ if (refusal !== undefined) {
215
+ if (!RECOVERY_COMMANDS.has(command)) {
216
+ this.sendError(socket, messageId, ErrorCode.endpointMapInvalid, endpointMapInvalidDetails(refusal));
217
+ return;
218
+ }
219
+ }
220
+ else if (command !== "attach" && !state.attached) {
221
+ // Gating: before `attach` the node has said nothing about which
222
+ // commands it knows, so `not_attached` is the honest answer even for
223
+ // a name it would otherwise reject (§1.1).
224
+ this.sendError(socket, messageId, ErrorCode.notAttached, `${command} requires a successful attach first`);
225
+ return;
226
+ }
227
+ const handler = this.#handlers.get(command);
228
+ if (handler === undefined) {
229
+ this.sendError(socket, messageId, ErrorCode.unknownCommand, `Unknown command ${command}`);
230
+ return;
231
+ }
232
+ try {
233
+ const result = await handler(commandArgs, socket, state);
234
+ if (!this.send(socket, { message_id: messageId, result })) {
235
+ // §1 promises exactly one response per request. A result we
236
+ // could not put on the wire — a value that will not stringify,
237
+ // a socket that failed mid-write — still owes the plugin an
238
+ // answer, and `message_id` is still in scope to address it.
239
+ this.sendError(socket, messageId, ErrorCode.internal, `Could not send the result of ${command}`);
240
+ }
241
+ }
242
+ catch (error) {
243
+ if (error instanceof ProtocolError) {
244
+ this.sendError(socket, messageId, error.code, error.message);
245
+ // §2: version skew fails closed — answer, then hang up.
246
+ if (error.code === ErrorCode.versionMismatch) {
247
+ socket.close();
248
+ }
249
+ return;
250
+ }
251
+ // Stack node-side, message on the wire: `details` is what the Indigo
252
+ // log shows a user, the stack is what we need to debug the node.
253
+ this.#log(`Command ${command} failed: ${describeErrorWithStack(error)}`);
254
+ this.sendError(socket, messageId, ErrorCode.internal, describeError(error));
255
+ }
256
+ }
257
+ async handleAttach(args, socket, state) {
258
+ const version = args.protocolVersion;
259
+ if (typeof version !== "number") {
260
+ throw new ProtocolError(ErrorCode.malformedArgs, "attach requires a numeric protocolVersion");
261
+ }
262
+ if (version !== PROTOCOL_VERSION) {
263
+ throw new ProtocolError(ErrorCode.versionMismatch, `Node speaks protocol version ${PROTOCOL_VERSION}, client sent ${version}`);
264
+ }
265
+ // §3.1: parse before attaching state changes hands, so a malformed
266
+ // endpoint set cannot supersede a healthy incumbent on its way to being
267
+ // rejected.
268
+ const endpoints = parseEndpointSpecs(args.endpoints);
269
+ const replaceAll = parseReplaceAll(args.intent);
270
+ // §2: exactly one attached client; a new attach supersedes the incumbent,
271
+ // which is how we recover from a half-open socket left by a plugin crash.
272
+ const incumbent = this.#attached;
273
+ if (incumbent !== undefined && incumbent !== socket) {
274
+ this.#log("Superseding previously attached client");
275
+ incumbent.close();
276
+ const incumbentState = this.#clients.get(incumbent);
277
+ if (incumbentState !== undefined) {
278
+ incumbentState.attached = false;
279
+ }
280
+ }
281
+ state.attached = true;
282
+ clearTimeout(state.unattachedTimer);
283
+ state.unattachedTimer = undefined;
284
+ this.#attached = socket;
285
+ const pluginVersion = typeof args.pluginVersion === "string" ? args.pluginVersion : "unknown";
286
+ this.#log(`Client attached (plugin ${pluginVersion}), reconciling ${endpoints.length} endpoint(s)`);
287
+ // §3.1: a fresh connection is always a full reconcile. The mass-removal
288
+ // guard lives behind the facade because only it knows the live set; a
289
+ // refusal leaves this client attached but the endpoint set untouched,
290
+ // which is what lets the plugin retry with an explicit intent.
291
+ return this.options.bridge.reconcile(endpoints, replaceAll);
292
+ }
293
+ async handleSetState(args) {
294
+ const indigoDeviceId = parseDeviceId(args.indigoDeviceId);
295
+ const states = args.states;
296
+ if (typeof states !== "object" || states === null || Array.isArray(states)) {
297
+ throw new ProtocolError(ErrorCode.malformedArgs, "states must be an object");
298
+ }
299
+ await this.options.bridge.setState(indigoDeviceId, states);
300
+ return {};
301
+ }
302
+ async handleSetReachable(args) {
303
+ const indigoDeviceId = parseDeviceId(args.indigoDeviceId);
304
+ if (typeof args.reachable !== "boolean") {
305
+ throw new ProtocolError(ErrorCode.malformedArgs, "reachable must be a boolean");
306
+ }
307
+ await this.options.bridge.setReachable(indigoDeviceId, args.reachable);
308
+ return {};
309
+ }
310
+ async handleOpenWindow(args) {
311
+ const duration = args.durationSeconds ?? WINDOW_DURATION_DEFAULT_SECONDS;
312
+ if (typeof duration !== "number" ||
313
+ !Number.isInteger(duration) ||
314
+ duration < WINDOW_DURATION_MIN_SECONDS ||
315
+ duration > WINDOW_DURATION_MAX_SECONDS) {
316
+ throw new ProtocolError(ErrorCode.malformedArgs, `durationSeconds must be an integer ${WINDOW_DURATION_MIN_SECONDS}-${WINDOW_DURATION_MAX_SECONDS}`);
317
+ }
318
+ return this.options.bridge.openCommissioningWindow(duration);
319
+ }
320
+ sendError(socket, messageId, code, details) {
321
+ this.send(socket, { message_id: messageId, error_code: code, details });
322
+ }
323
+ /**
324
+ * Write one frame, reporting whether it went.
325
+ *
326
+ * Never throws: a serialisation failure here would otherwise escape into
327
+ * whatever was mid-flight (an observable, a handler chain) rather than into
328
+ * the response the caller is trying to send.
329
+ */
330
+ send(socket, frame) {
331
+ if (socket.readyState !== socket.OPEN) {
332
+ // Almost always the superseded incumbent: §2 closes it the moment a
333
+ // new client attaches, and anything already queued for it lands in
334
+ // that CLOSING window. Worth a line — it is also what a genuinely
335
+ // wedged socket looks like.
336
+ this.#log(`Dropping a frame for a socket in readyState ${socket.readyState} (not OPEN)`);
337
+ return false;
338
+ }
339
+ try {
340
+ socket.send(JSON.stringify(frame));
341
+ return true;
342
+ }
343
+ catch (error) {
344
+ this.#log(`Failed to send frame: ${describeErrorWithStack(error)}`);
345
+ return false;
346
+ }
347
+ }
348
+ }
349
+ //# sourceMappingURL=ws-server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ws-server.js","sourceRoot":"","sources":["../src/ws-server.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,EAAE,eAAe,EAAkB,MAAM,IAAI,CAAC;AAErD,OAAO,EAEH,aAAa,EACb,sBAAsB,EACtB,yBAAyB,EACzB,SAAS,EAET,SAAS,EAIT,gBAAgB,EAChB,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,+BAA+B,EAC/B,2BAA2B,EAC3B,2BAA2B,GAC9B,MAAM,eAAe,CAAC;AACvB,OAAO,EACH,aAAa,EACb,iBAAiB,EACjB,kBAAkB,EAClB,gBAAgB,EAChB,4BAA4B,EAC5B,eAAe,GAClB,MAAM,gBAAgB,CAAC;AAExB,MAAM,CAAC,MAAM,aAAa,GAAG,WAAW,CAAC;AA+BzC,MAAM,OAAO,cAAc;IAOM;IAN7B,IAAI,CAAmB;IACvB,SAAS,CAAa;IACb,QAAQ,GAAG,IAAI,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.5.0",
4
+ "description": "Matter bridge node for the indigo-matter Indigo plugin — exports selected Indigo devices as Matter accessories.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "dist/main.js",
8
+ "bin": {
9
+ "indigo-matter-bridge": "dist/main.js"
10
+ },
11
+ "files": [
12
+ "dist"
13
+ ],
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/simons-plugins/indigo-matter.git",
17
+ "directory": "bridge-node"
18
+ },
19
+ "homepage": "https://github.com/simons-plugins/indigo-matter",
20
+ "keywords": [
21
+ "matter",
22
+ "matter.js",
23
+ "indigo",
24
+ "bridge",
25
+ "home-automation"
26
+ ],
27
+ "engines": {
28
+ "node": ">=22.13.0"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc",
32
+ "prepublishOnly": "npm run clean && npm run build",
33
+ "start": "node dist/main.js",
34
+ "test": "tsc && tsc -p tsconfig.test.json && rm -rf .test-build/test/fixtures && mkdir -p .test-build/test/fixtures && cp -R ../tests/fixtures/bridge_protocol .test-build/test/fixtures/bridge_protocol && node --test --test-force-exit \".test-build/test/*.test.js\"",
35
+ "clean": "rm -rf dist .test-build"
36
+ },
37
+ "dependencies": {
38
+ "@matter/main": "0.17.8",
39
+ "@matter/nodejs": "0.17.8",
40
+ "ws": "8.21.2"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^22.20.1",
44
+ "@types/ws": "^8.18.1",
45
+ "typescript": "^5.9.3"
46
+ }
47
+ }