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.
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Argument parsing and the reconcile planner for the endpoint-CRUD commands
3
+ * (BRIDGE_PROTOCOL §3.1-§3.5, §4.1).
4
+ *
5
+ * Deliberately matter.js-free, like `protocol.ts`: every §1.1 refusal the
6
+ * endpoint commands can produce — `malformed_args`, `unknown_role`,
7
+ * `mass_removal_refused` — is decided here, so the decisions are unit-testable
8
+ * without a Matter stack and the WebSocket server and the test double reach the
9
+ * same verdicts from the same code.
10
+ */
11
+ import { ErrorCode, INTENT_REPLACE_ALL, isRole, ProtocolError, } from "./protocol.js";
12
+ /** True for a plain JSON object — the shape `states`/`options` must have. */
13
+ function isStruct(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function requireStruct(value, what) {
17
+ if (value === undefined) {
18
+ return {};
19
+ }
20
+ if (!isStruct(value)) {
21
+ throw new ProtocolError(ErrorCode.malformedArgs, `${what} must be an object`);
22
+ }
23
+ return value;
24
+ }
25
+ /**
26
+ * §1.1 gate for the identity key. Every endpoint command carries one, and it is
27
+ * always the same refusal, so it is one function rather than four copies.
28
+ */
29
+ export function parseDeviceId(value) {
30
+ if (typeof value !== "number" || !Number.isInteger(value)) {
31
+ throw new ProtocolError(ErrorCode.malformedArgs, "indigoDeviceId must be an integer");
32
+ }
33
+ return value;
34
+ }
35
+ /**
36
+ * Parse one wire `EndpointSpec` (§4.1).
37
+ *
38
+ * A role outside the §4.2 enum is `unknown_role`, not `malformed_args`: §1.1
39
+ * gives it its own code precisely so the plugin can tell "you sent nonsense"
40
+ * from "this node is older than your role vocabulary".
41
+ */
42
+ export function parseEndpointSpec(value) {
43
+ if (!isStruct(value)) {
44
+ throw new ProtocolError(ErrorCode.malformedArgs, "endpoint must be an object");
45
+ }
46
+ const indigoDeviceId = parseDeviceId(value.indigoDeviceId);
47
+ if (typeof value.role !== "string") {
48
+ throw new ProtocolError(ErrorCode.malformedArgs, "endpoint.role must be a string");
49
+ }
50
+ if (!isRole(value.role)) {
51
+ throw new ProtocolError(ErrorCode.unknownRole, `role ${value.role} is not in the v1 role enum (§4.2)`);
52
+ }
53
+ if (typeof value.label !== "string") {
54
+ throw new ProtocolError(ErrorCode.malformedArgs, "endpoint.label must be a string");
55
+ }
56
+ // `reachable` defaults to true: an omitted flag means "nothing said about
57
+ // availability", and an accessory that greys itself out by default would be
58
+ // the worse reading.
59
+ const reachable = value.reachable === undefined ? true : value.reachable;
60
+ if (typeof reachable !== "boolean") {
61
+ throw new ProtocolError(ErrorCode.malformedArgs, "endpoint.reachable must be a boolean");
62
+ }
63
+ return {
64
+ indigoDeviceId,
65
+ role: value.role,
66
+ label: value.label,
67
+ reachable,
68
+ states: requireStruct(value.states, "endpoint.states"),
69
+ options: requireStruct(value.options, "endpoint.options"),
70
+ };
71
+ }
72
+ /** Parse the `endpoints` array of an `attach` (§3.1). */
73
+ export function parseEndpointSpecs(value) {
74
+ if (value === undefined) {
75
+ return [];
76
+ }
77
+ if (!Array.isArray(value)) {
78
+ throw new ProtocolError(ErrorCode.malformedArgs, "endpoints must be an array");
79
+ }
80
+ const specs = value.map(parseEndpointSpec);
81
+ const seen = new Set();
82
+ for (const spec of specs) {
83
+ if (seen.has(spec.indigoDeviceId)) {
84
+ throw new ProtocolError(ErrorCode.malformedArgs, `endpoints contains indigoDeviceId ${spec.indigoDeviceId} twice`);
85
+ }
86
+ seen.add(spec.indigoDeviceId);
87
+ }
88
+ return specs;
89
+ }
90
+ /** §3.9: the fabric to drop. `fabricIndex` is a 1-based Matter fabric index. */
91
+ export function parseFabricIndex(value) {
92
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
93
+ throw new ProtocolError(ErrorCode.malformedArgs, `fabricIndex must be a positive integer, got ${JSON.stringify(value)}`);
94
+ }
95
+ return value;
96
+ }
97
+ /**
98
+ * §3.10: whether a factory reset keeps `endpoint-map.json`.
99
+ *
100
+ * Absent means `true` — the §6.6 rule that destructive operations cannot happen
101
+ * as a default. Discarding endpoint identity is the destructive half of this
102
+ * command, so it takes an explicit `false`; a client that omits the flag gets
103
+ * the reset it asked for and keeps the identities it did not mention.
104
+ */
105
+ export function parsePreserveEndpointNumbers(value) {
106
+ if (value === undefined) {
107
+ return true;
108
+ }
109
+ if (typeof value !== "boolean") {
110
+ throw new ProtocolError(ErrorCode.malformedArgs, "preserveEndpointNumbers must be a boolean");
111
+ }
112
+ return value;
113
+ }
114
+ /** §3.1: the opt-in that makes emptying the endpoint set deliberate. */
115
+ export function parseReplaceAll(intent) {
116
+ if (intent === undefined) {
117
+ return false;
118
+ }
119
+ if (typeof intent !== "string") {
120
+ throw new ProtocolError(ErrorCode.malformedArgs, "intent must be a string");
121
+ }
122
+ return intent === INTENT_REPLACE_ALL;
123
+ }
124
+ /**
125
+ * Diff the desired set against the live one, enforcing the §3.1 mass-removal
126
+ * guard.
127
+ *
128
+ * The guard is about the *effect*, not the literal empty array: an `attach`
129
+ * carrying a completely disjoint device set would also remove every live
130
+ * endpoint, and that is just as much "every exported accessory disappears from
131
+ * every paired ecosystem" as `endpoints: []` is.
132
+ */
133
+ export function planReconcile(live, desired, replaceAll) {
134
+ const plan = { create: [], update: [], recreate: [], remove: [] };
135
+ const desiredIds = new Set();
136
+ for (const spec of desired) {
137
+ desiredIds.add(spec.indigoDeviceId);
138
+ const liveRole = live.get(spec.indigoDeviceId);
139
+ if (liveRole === undefined) {
140
+ plan.create.push(spec);
141
+ }
142
+ else if (liveRole === spec.role) {
143
+ plan.update.push(spec);
144
+ }
145
+ else {
146
+ plan.recreate.push(spec);
147
+ }
148
+ }
149
+ for (const indigoDeviceId of live.keys()) {
150
+ if (!desiredIds.has(indigoDeviceId)) {
151
+ plan.remove.push(indigoDeviceId);
152
+ }
153
+ }
154
+ // A `recreate` is not a removal: the device stays exported, it just changes
155
+ // accessory type. Counting it as one would refuse a lawful role correction
156
+ // on a single-export bridge.
157
+ const survivors = live.size - plan.remove.length;
158
+ if (live.size > 0 && survivors === 0 && !replaceAll) {
159
+ throw new ProtocolError(ErrorCode.massRemovalRefused, `attach would remove all ${live.size} live endpoints without intent: ${INTENT_REPLACE_ALL}`);
160
+ }
161
+ return plan;
162
+ }
163
+ //# sourceMappingURL=reconcile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reconcile.js","sourceRoot":"","sources":["../src/reconcile.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAEH,SAAS,EACT,kBAAkB,EAClB,MAAM,EACN,aAAa,GAEhB,MAAM,eAAe,CAAC;AAEvB,6EAA6E;AAC7E,SAAS,QAAQ,CAAC,KAAc;IAC5B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,aAAa,CAAC,KAAc,EAAE,IAAY;IAC/C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACtB,OAAO,EAAE,CAAC;IACd,CAAC;IACD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACnB,MAAM,IAAI,aAAa,CAAC,SAAS,CAAC,aAAa,EAAE,GAAG,IAAI,oBAAoB,CAAC,CAAC;IAClF,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,KAAc;IACxC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QACxD,MAAM,IAAI,aAAa,CAAC,SAAS,CAAC,aAAa,EAAE,mCAAmC,CAAC,CAAC;IAC1F,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAAC,KAAc;IAC5C,I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AC,CAAC;QAC7B,CAAC;IACL,CAAC;IAED,KAAK,MAAM,cAAc,IAAI,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;QACvC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAClC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACrC,CAAC;IACL,CAAC;IAED,4EAA4E;IAC5E,2EAA2E;IAC3E,6BAA6B;IAC7B,MAAM,SAAS,GAAG,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC;IACjD,IAAI,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,SAAS,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;QAClD,MAAM,IAAI,aAAa,CACnB,SAAS,CAAC,kBAAkB,EAC5B,2BAA2B,IAAI,CAAC,IAAI,mCAAmC,kBAAkB,EAAE,CAC9F,CAAC;IACN,CAAC;IAED,OAAO,IAAI,CAAC;AAChB,CAAC"}
@@ -0,0 +1,122 @@
1
+ /**
2
+ * The live bridged-endpoint set: create, update, remove, and the §3.1 reconcile.
3
+ *
4
+ * Split out of `node.ts` so that module stays what it is — the Matter *node*
5
+ * (identity, commissioning, fabrics) — while this one owns the *children*.
6
+ * Both are matter.js-coupled; the protocol layer reaches them only through
7
+ * `BridgeFacade`.
8
+ */
9
+ import type { Endpoint } from "@matter/main";
10
+ import { type BridgedIdentity } from "./endpoints.js";
11
+ import { type CommandEventData, type EndpointSpec, type EndpointSummary, type RemoveResult, type RoleValue, type UpsertResult } from "./protocol.js";
12
+ /**
13
+ * PRD §5.3: bulk removals are paced so controllers see one subscription update
14
+ * each rather than a burst they may coalesce or drop.
15
+ */
16
+ export declare const REMOVAL_PACING_MS = 100;
17
+ export interface EndpointRegistryOptions {
18
+ /** The aggregator every bridged child is added to. */
19
+ aggregator: Endpoint;
20
+ /** Sink for §5 `command` events. */
21
+ emit: (data: CommandEventData) => void;
22
+ log?: (message: string) => void;
23
+ /**
24
+ * The identity fields every child's Bridged Device Basic Information carries
25
+ * — vendor, product, hardware and software versions. Bridge-wide, not
26
+ * per-device: Indigo does not know who made a relay.
27
+ */
28
+ bridgeIdentity: BridgedIdentity;
29
+ /** Injectable so the pacing test does not take a real 100ms per removal. */
30
+ removalPacingMs?: number;
31
+ /**
32
+ * Called once per add/remove batch so the caller can bump
33
+ * `ConfigurationVersion`. Optional because the pure-registry tests have no
34
+ * root node to bump.
35
+ */
36
+ onConfigurationChange?: () => Promise<void>;
37
+ }
38
+ export declare class EndpointRegistry {
39
+ #private;
40
+ private readonly options;
41
+ constructor(options: EndpointRegistryOptions);
42
+ /**
43
+ * Run one mutation with the registry to itself.
44
+ *
45
+ * Every mutating entry point goes through here, because two of them running
46
+ * at once share both `#live` and the aggregator and neither is transactional.
47
+ * The case that forced it is not exotic: a plugin crash leaves a half-open
48
+ * socket, launchd restarts the plugin, and the new process `attach`es on a
49
+ * *new* socket while the incumbent's reconcile is still mid-flight — and a
50
+ * reconcile that paces bulk removals (PRD §5.3, ~100ms each) holds the
51
+ * registry for seconds. Without this, the second reconcile plans its diff
52
+ * from a snapshot the first is still mutating underneath it, and the two
53
+ * interleave into a live set that matches neither request.
54
+ *
55
+ * A plain promise chain rather than a lock class: there is exactly one
56
+ * critical section (the whole registry), so ordering is the only thing to
57
+ * decide, and FIFO is what §1's in-receipt-order guarantee already promises
58
+ * the plugin.
59
+ */
60
+ private serialize;
61
+ /** §4.3 `StatusReport.endpoints`, in device-id order for a stable readout. */
62
+ summaries(): EndpointSummary[];
63
+ get size(): number;
64
+ /** The live role of a device, or undefined — what the reconcile planner diffs. */
65
+ liveRoles(): Map<number, RoleValue>;
66
+ /**
67
+ * §3.1: full reconcile against the desired set.
68
+ *
69
+ * Refusals that can be decided from the plan alone — an unsupported role,
70
+ * `mass_removal_refused` — are thrown before anything is touched: those are
71
+ * gates, and a gate that half-applies is not a gate.
72
+ *
73
+ * Once mutation starts there is no such promise. matter.js gives us no
74
+ * transaction across several `add`/`close` calls, so a failure part-way
75
+ * through leaves a live set that is neither the old one nor the requested
76
+ * one. What we owe the plugin then is an honest account of it, which is the
77
+ * `reconcile aborted after N/M` line below plus the `internal` refusal —
78
+ * **the plugin should follow a failed `attach` with `get_status`** rather
79
+ * than assume either set.
80
+ */
81
+ reconcile(desired: readonly EndpointSpec[], replaceAll: boolean): Promise<void>;
82
+ private reconcileNow;
83
+ /** §3.2 — create-or-update, idempotent, `role_change` on a role mismatch. */
84
+ upsert(spec: EndpointSpec): Promise<UpsertResult>;
85
+ /** §3.3 — idempotent removal. The endpoint-number allocation is retained. */
86
+ remove(indigoDeviceId: number): Promise<RemoveResult>;
87
+ /** §3.4 — role-specific state keys, applied as local writes. */
88
+ setState(indigoDeviceId: number, states: Record<string, unknown>): Promise<void>;
89
+ /** §3.5 */
90
+ setReachable(indigoDeviceId: number, reachable: boolean): Promise<void>;
91
+ /** Drop every listener. The endpoints themselves die with the ServerNode. */
92
+ close(): void;
93
+ private require;
94
+ private assertSupported;
95
+ private create;
96
+ /** Label, reachability and state — everything an existing endpoint can change. */
97
+ private update;
98
+ /**
99
+ * Close one endpoint and, only if that worked, forget it.
100
+ *
101
+ * The order is the whole point. Evicting first and closing after means a
102
+ * throwing `close()` leaves an accessory that is still in the Matter tree
103
+ * and still visible in every paired ecosystem, but that the registry denies
104
+ * exists: taps on it produce no `command` events, and the plugin's retry
105
+ * gets `{removed: false}` — a §3.3-idempotent *success* — so nothing ever
106
+ * reports the zombie. Closing first makes the failure a failure: the entry
107
+ * stays, its listeners are put back, and the plugin sees `internal` on a
108
+ * call it can honestly retry.
109
+ */
110
+ private closeOne;
111
+ /**
112
+ * PRD §5.3: ~100ms apart, so each removal is its own subscription update.
113
+ *
114
+ * `onRemoved` rather than a return count because the count matters most
115
+ * when this *throws*: a mid-batch failure aborts the remaining removals,
116
+ * and a returned tally would be thrown away exactly when §3.1's partial-
117
+ * failure account needs it. The state {@link closeOne} restored is intact
118
+ * either way; `reconcile` reports how far it got.
119
+ */
120
+ private removeMany;
121
+ private noteConfigurationChange;
122
+ }
@@ -0,0 +1,314 @@
1
+ /**
2
+ * The live bridged-endpoint set: create, update, remove, and the §3.1 reconcile.
3
+ *
4
+ * Split out of `node.ts` so that module stays what it is — the Matter *node*
5
+ * (identity, commissioning, fabrics) — while this one owns the *children*.
6
+ * Both are matter.js-coupled; the protocol layer reaches them only through
7
+ * `BridgeFacade`.
8
+ */
9
+ import { applyLabel, applyReachable, applyStates, createEndpoint, isSupportedRole, UNSUPPORTED_ROLE_DETAILS, watchCommands, } from "./endpoints.js";
10
+ import { describeError, describeErrorWithStack, ErrorCode, ProtocolError, } from "./protocol.js";
11
+ import { planReconcile } from "./reconcile.js";
12
+ /**
13
+ * PRD §5.3: bulk removals are paced so controllers see one subscription update
14
+ * each rather than a burst they may coalesce or drop.
15
+ */
16
+ export const REMOVAL_PACING_MS = 100;
17
+ export class EndpointRegistry {
18
+ options;
19
+ #live = new Map();
20
+ #log;
21
+ #pacingMs;
22
+ /** Tail of the mutation chain — see {@link serialize}. */
23
+ #queue = Promise.resolve();
24
+ /**
25
+ * Names of the mutations on the chain, head first. Pushed *synchronously*
26
+ * on the way in, because the whole point is to notice a second caller that
27
+ * arrived before the first one's continuation has even been scheduled —
28
+ * a flag set inside the queued callback would still read "idle" then.
29
+ */
30
+ #waiting = [];
31
+ constructor(options) {
32
+ this.options = options;
33
+ this.#log = options.log ?? (() => { });
34
+ this.#pacingMs = options.removalPacingMs ?? REMOVAL_PACING_MS;
35
+ }
36
+ /**
37
+ * Run one mutation with the registry to itself.
38
+ *
39
+ * Every mutating entry point goes through here, because two of them running
40
+ * at once share both `#live` and the aggregator and neither is transactional.
41
+ * The case that forced it is not exotic: a plugin crash leaves a half-open
42
+ * socket, launchd restarts the plugin, and the new process `attach`es on a
43
+ * *new* socket while the incumbent's reconcile is still mid-flight — and a
44
+ * reconcile that paces bulk removals (PRD §5.3, ~100ms each) holds the
45
+ * registry for seconds. Without this, the second reconcile plans its diff
46
+ * from a snapshot the first is still mutating underneath it, and the two
47
+ * interleave into a live set that matches neither request.
48
+ *
49
+ * A plain promise chain rather than a lock class: there is exactly one
50
+ * critical section (the whole registry), so ordering is the only thing to
51
+ * decide, and FIFO is what §1's in-receipt-order guarantee already promises
52
+ * the plugin.
53
+ */
54
+ serialize(what, run) {
55
+ const ahead = this.#waiting[0];
56
+ if (ahead !== undefined) {
57
+ // Loud on purpose: this is the plugin-crash-restart window, and it
58
+ // is the only explanation for an attach that appears to hang.
59
+ this.#log(`${what} is waiting for an unfinished ${ahead} to release the registry`);
60
+ }
61
+ this.#waiting.push(what);
62
+ const result = this.#queue.then(async () => {
63
+ try {
64
+ return await run();
65
+ }
66
+ finally {
67
+ this.#waiting.shift();
68
+ }
69
+ });
70
+ // The chain must never be left rejected, or one refusal would poison
71
+ // every command behind it. The caller still gets the rejection.
72
+ this.#queue = result.then(() => undefined, () => undefined);
73
+ return result;
74
+ }
75
+ /** §4.3 `StatusReport.endpoints`, in device-id order for a stable readout. */
76
+ summaries() {
77
+ return [...this.#live.entries()]
78
+ .map(([indigoDeviceId, live]) => ({
79
+ indigoDeviceId,
80
+ endpointNumber: Number(live.endpoint.number),
81
+ role: live.role,
82
+ }))
83
+ .sort((a, b) => a.indigoDeviceId - b.indigoDeviceId);
84
+ }
85
+ get size() {
86
+ return this.#live.size;
87
+ }
88
+ /** The live role of a device, or undefined — what the reconcile planner diffs. */
89
+ liveRoles() {
90
+ return new Map([...this.#live.entries()].map(([id, live]) => [id, live.role]));
91
+ }
92
+ /**
93
+ * §3.1: full reconcile against the desired set.
94
+ *
95
+ * Refusals that can be decided from the plan alone — an unsupported role,
96
+ * `mass_removal_refused` — are thrown before anything is touched: those are
97
+ * gates, and a gate that half-applies is not a gate.
98
+ *
99
+ * Once mutation starts there is no such promise. matter.js gives us no
100
+ * transaction across several `add`/`close` calls, so a failure part-way
101
+ * through leaves a live set that is neither the old one nor the requested
102
+ * one. What we owe the plugin then is an honest account of it, which is the
103
+ * `reconcile aborted after N/M` line below plus the `internal` refusal —
104
+ * **the plugin should follow a failed `attach` with `get_status`** rather
105
+ * than assume either set.
106
+ */
107
+ async reconcile(desired, replaceAll) {
108
+ return this.serialize("reconcile", () => this.reconcileNow(desired, replaceAll));
109
+ }
110
+ async reconcileNow(desired, replaceAll) {
111
+ for (const spec of desired) {
112
+ this.assertSupported(spec.role);
113
+ }
114
+ const plan = planReconcile(this.liveRoles(), desired, replaceAll);
115
+ for (const indigoDeviceId of plan.recreate.map(spec => spec.indigoDeviceId)) {
116
+ // §4.1 rejects a role change through `upsert_endpoint`; attach is the
117
+ // reconcile path and does it the only way Matter allows, which is a
118
+ // new accessory. Loud, because ecosystems lose the old one's name.
119
+ this.#log(`Recreating endpoint ${indigoDeviceId}: role changed`);
120
+ }
121
+ const removals = [...plan.remove, ...plan.recreate.map(spec => spec.indigoDeviceId)];
122
+ const total = removals.length + plan.create.length + plan.recreate.length + plan.update.length;
123
+ let done = 0;
124
+ let mutated = false;
125
+ try {
126
+ await this.removeMany(removals, () => {
127
+ mutated = true;
128
+ done += 1;
129
+ });
130
+ for (const spec of [...plan.create, ...plan.recreate]) {
131
+ await this.create(spec);
132
+ mutated = true;
133
+ done += 1;
134
+ }
135
+ for (const spec of plan.update) {
136
+ await this.update(spec);
137
+ done += 1;
138
+ }
139
+ }
140
+ catch (error) {
141
+ // A part-applied reconcile still changed the bridged-node set, so
142
+ // controllers still need the nudge — skipping the bump because the
143
+ // batch failed is how a half-applied set becomes an invisible one.
144
+ if (mutated) {
145
+ await this.noteConfigurationChange();
146
+ }
147
+ this.#log(`reconcile aborted after ${done}/${total} operations; ` +
148
+ `live set now [${[...this.#live.keys()].sort((a, b) => a - b).join(", ")}] ` +
149
+ `(requested [${desired.map(spec => spec.indigoDeviceId).join(", ")}])`);
150
+ throw error;
151
+ }
152
+ if (plan.create.length > 0 || plan.recreate.length > 0 || plan.remove.length > 0) {
153
+ await this.noteConfigurationChange();
154
+ }
155
+ this.#log(`Reconciled endpoints: ${plan.create.length} created, ${plan.update.length} updated, ` +
156
+ `${plan.recreate.length} recreated, ${plan.remove.length} removed (${this.#live.size} live)`);
157
+ }
158
+ /** §3.2 — create-or-update, idempotent, `role_change` on a role mismatch. */
159
+ async upsert(spec) {
160
+ return this.serialize("upsert_endpoint", async () => {
161
+ this.assertSupported(spec.role);
162
+ const existing = this.#live.get(spec.indigoDeviceId);
163
+ if (existing === undefined) {
164
+ const created = await this.create(spec);
165
+ await this.noteConfigurationChange();
166
+ return { endpointNumber: Number(created.number) };
167
+ }
168
+ if (existing.role !== spec.role) {
169
+ throw new ProtocolError(ErrorCode.roleChange, `endpoint ${spec.indigoDeviceId} is ${existing.role}; remove and re-add to change role`);
170
+ }
171
+ await this.update(spec);
172
+ return { endpointNumber: Number(existing.endpoint.number) };
173
+ });
174
+ }
175
+ /** §3.3 — idempotent removal. The endpoint-number allocation is retained. */
176
+ async remove(indigoDeviceId) {
177
+ return this.serialize("remove_endpoint", async () => {
178
+ const live = this.#live.get(indigoDeviceId);
179
+ if (live === undefined) {
180
+ return { removed: false };
181
+ }
182
+ await this.closeOne(indigoDeviceId, live);
183
+ await this.noteConfigurationChange();
184
+ return { removed: true };
185
+ });
186
+ }
187
+ /** §3.4 — role-specific state keys, applied as local writes. */
188
+ async setState(indigoDeviceId, states) {
189
+ return this.serialize("set_state", async () => {
190
+ const live = this.require(indigoDeviceId);
191
+ await applyStates(live.endpoint, live.role, states);
192
+ });
193
+ }
194
+ /** §3.5 */
195
+ async setReachable(indigoDeviceId, reachable) {
196
+ return this.serialize("set_reachable", async () => {
197
+ const live = this.require(indigoDeviceId);
198
+ await applyReachable(live.endpoint, reachable);
199
+ });
200
+ }
201
+ /** Drop every listener. The endpoints themselves die with the ServerNode. */
202
+ close() {
203
+ for (const live of this.#live.values()) {
204
+ live.unwatch();
205
+ }
206
+ this.#live.clear();
207
+ }
208
+ require(indigoDeviceId) {
209
+ const live = this.#live.get(indigoDeviceId);
210
+ if (live === undefined) {
211
+ throw new ProtocolError(ErrorCode.unknownDevice, `no live endpoint for indigoDeviceId ${indigoDeviceId}`);
212
+ }
213
+ return live;
214
+ }
215
+ assertSupported(role) {
216
+ if (!isSupportedRole(role)) {
217
+ throw new ProtocolError(ErrorCode.internal, UNSUPPORTED_ROLE_DETAILS(role));
218
+ }
219
+ }
220
+ async create(spec) {
221
+ const endpoint = createEndpoint(spec, this.options.bridgeIdentity);
222
+ await this.options.aggregator.add(endpoint);
223
+ let unwatch;
224
+ try {
225
+ unwatch = watchCommands(endpoint, spec, this.options.emit, this.#log);
226
+ }
227
+ catch (error) {
228
+ // The endpoint is already in the Matter tree but will never be in
229
+ // `#live`: take it back out rather than leave an accessory the
230
+ // registry does not know about (the same zombie {@link closeOne}
231
+ // exists to prevent, from the other end).
232
+ await endpoint.close().catch(() => undefined);
233
+ throw error;
234
+ }
235
+ this.#live.set(spec.indigoDeviceId, { endpoint, role: spec.role, unwatch });
236
+ this.#log(`Endpoint ${spec.indigoDeviceId} (${spec.role}) added as number ${Number(endpoint.number)}`);
237
+ return endpoint;
238
+ }
239
+ /** Label, reachability and state — everything an existing endpoint can change. */
240
+ async update(spec) {
241
+ const live = this.require(spec.indigoDeviceId);
242
+ // Both labels, because {@link applyLabel} writes both: comparing only
243
+ // `nodeLabel` would call an endpoint up to date while its `productLabel`
244
+ // still showed the name from two renames ago.
245
+ const info = live.endpoint.stateOf("bridgedDeviceBasicInformation");
246
+ if (info.nodeLabel !== spec.label || info.productLabel !== spec.label) {
247
+ await applyLabel(live.endpoint, spec.label);
248
+ }
249
+ await applyReachable(live.endpoint, spec.reachable);
250
+ await applyStates(live.endpoint, live.role, spec.states);
251
+ }
252
+ /**
253
+ * Close one endpoint and, only if that worked, forget it.
254
+ *
255
+ * The order is the whole point. Evicting first and closing after means a
256
+ * throwing `close()` leaves an accessory that is still in the Matter tree
257
+ * and still visible in every paired ecosystem, but that the registry denies
258
+ * exists: taps on it produce no `command` events, and the plugin's retry
259
+ * gets `{removed: false}` — a §3.3-idempotent *success* — so nothing ever
260
+ * reports the zombie. Closing first makes the failure a failure: the entry
261
+ * stays, its listeners are put back, and the plugin sees `internal` on a
262
+ * call it can honestly retry.
263
+ */
264
+ async closeOne(indigoDeviceId, live) {
265
+ // Unwatch first so a close-time attribute change cannot emit a command
266
+ // for an endpoint on its way out; restored below if the close fails.
267
+ live.unwatch();
268
+ try {
269
+ await live.endpoint.close();
270
+ }
271
+ catch (error) {
272
+ live.unwatch = watchCommands(live.endpoint, { indigoDeviceId, role: live.role }, this.options.emit, this.#log);
273
+ this.#log(`Endpoint ${indigoDeviceId} failed to close; registry and Matter tree may disagree: ` +
274
+ describeErrorWithStack(error));
275
+ throw new ProtocolError(ErrorCode.internal, `endpoint ${indigoDeviceId} failed to close: ${describeError(error)}`);
276
+ }
277
+ this.#live.delete(indigoDeviceId);
278
+ this.#log(`Endpoint ${indigoDeviceId} removed`);
279
+ }
280
+ /**
281
+ * PRD §5.3: ~100ms apart, so each removal is its own subscription update.
282
+ *
283
+ * `onRemoved` rather than a return count because the count matters most
284
+ * when this *throws*: a mid-batch failure aborts the remaining removals,
285
+ * and a returned tally would be thrown away exactly when §3.1's partial-
286
+ * failure account needs it. The state {@link closeOne} restored is intact
287
+ * either way; `reconcile` reports how far it got.
288
+ */
289
+ async removeMany(indigoDeviceIds, onRemoved) {
290
+ for (const [index, indigoDeviceId] of indigoDeviceIds.entries()) {
291
+ const live = this.#live.get(indigoDeviceId);
292
+ if (live === undefined) {
293
+ continue;
294
+ }
295
+ await this.closeOne(indigoDeviceId, live);
296
+ onRemoved();
297
+ if (index < indigoDeviceIds.length - 1 && this.#pacingMs > 0) {
298
+ await new Promise(resolve => setTimeout(resolve, this.#pacingMs));
299
+ }
300
+ }
301
+ }
302
+ async noteConfigurationChange() {
303
+ try {
304
+ await this.options.onConfigurationChange?.();
305
+ }
306
+ catch (error) {
307
+ // A ConfigurationVersion bump is a hint to controllers, not a
308
+ // correctness requirement: failing the whole command over it would
309
+ // turn a cosmetic problem into a broken export.
310
+ this.#log(`Could not bump ConfigurationVersion: ${String(error)}`);
311
+ }
312
+ }
313
+ }
314
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.js","sourceRoot":"","sources":["../src/registry.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,EACH,UAAU,EACV,cAAc,EACd,WAAW,EAEX,cAAc,EACd,eAAe,EACf,wBAAwB,EACxB,aAAa,GAChB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAEH,aAAa,EACb,sBAAsB,EAGtB,SAAS,EACT,aAAa,GAIhB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;GAGG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AA+BrC,MAAM,OAAO,gBAAgB;IAcI;IAbpB,KAAK,GAAG,IAAI,GAAG,EAAwB,CAAC;IACxC,IAAI,CAA4B;IAChC,SAAS,CAAS;IAC3B,0DAA0D;IAC1D,MAAM,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC1C;;;;;OAKG;IACM,QAAQ,GAAa,EAAE,CAAC;IAEjC,YAA6B,OAAgC;QAAhC,YAAO,GAAP,OAAO,CAAyB;QACzD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QACtC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,eAAe,IAAI,iBAAiB,CAAC;IAClE,CAAC;IAED;;;;;;;;;;;;;;;;;OAiBG;IACK,SAAS,CAAI,IAAY,EAAE,GAAqB;QACpD,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,mEAAmE;YACnE,8DAA8D;YAC9D,IAAI,CAAC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