@sdeck/plugin-home-assistant 0.0.0-stage → 0.2.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,33 @@
1
+ /** A client for Home Assistant's WebSocket API, authenticated with a long-lived access token. */
2
+ import { type Link } from "@sdeck/plugin";
3
+ export interface EntityState {
4
+ state: string;
5
+ /** The friendly name, or the entity id. */
6
+ name: string;
7
+ attributes: Record<string, unknown>;
8
+ }
9
+ /** Entities by domain and object id: `entities.light.kitchen.state`. */
10
+ export type Entities = Record<string, Record<string, EntityState>>;
11
+ export interface HaClient {
12
+ /** Sends a command; resolves with its result. */
13
+ command(message: {
14
+ type: string;
15
+ [key: string]: unknown;
16
+ }): Promise<unknown>;
17
+ /** The entities, kept current. */
18
+ entities(): Entities;
19
+ /** Hears every state change; returns a function that stops. */
20
+ onChange(listener: (change: StateChange) => void): () => void;
21
+ }
22
+ export interface StateChange {
23
+ entity: string;
24
+ /** `undefined` when the entity is gone. */
25
+ state: EntityState | undefined;
26
+ from: string | undefined;
27
+ }
28
+ /** `http://host:8123` → `ws://host:8123/api/websocket`. */
29
+ export declare function socketUrl(address: string): string;
30
+ /** A copy of `entities` with one entity set or removed. */
31
+ export declare function withEntity(entities: Entities, id: string, state: EntityState | undefined): Entities;
32
+ export declare function connectHomeAssistant(address: string, token: string, lost: (error: Error) => void, signal: AbortSignal, pingMs?: number): Promise<Link<HaClient>>;
33
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,OAAO,EAAE,KAAK,IAAI,EAAkB,MAAM,eAAe,CAAC;AAE1D,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAED,wEAAwE;AACxE,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;AAEnE,MAAM,WAAW,QAAQ;IACvB,iDAAiD;IACjD,OAAO,CAAC,OAAO,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7E,kCAAkC;IAClC,QAAQ,IAAI,QAAQ,CAAC;IACrB,+DAA+D;IAC/D,QAAQ,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAC/D;AAED,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,2CAA2C;IAC3C,KAAK,EAAE,WAAW,GAAG,SAAS,CAAC;IAC/B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CASjD;AAiBD,2DAA2D;AAC3D,wBAAgB,UAAU,CACxB,QAAQ,EAAE,QAAQ,EAClB,EAAE,EAAE,MAAM,EACV,KAAK,EAAE,WAAW,GAAG,SAAS,GAC7B,QAAQ,CASV;AAED,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,EACb,IAAI,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,EAC5B,MAAM,EAAE,WAAW,EACnB,MAAM,SAAS,GACd,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAwJzB"}
@@ -0,0 +1,14 @@
1
+ export * from "./client.ts";
2
+ /** `light.kitchen` → the entity's domain and object id, or a message for the user. */
3
+ export declare function splitEntity(entity: string): {
4
+ domain: string;
5
+ object: string;
6
+ };
7
+ /** The state path of an entity, for templates and expressions. */
8
+ export declare function entityPath(entity: string): string;
9
+ export declare const domainOf: (entity: string) => string;
10
+ /** The data of a service call: a JSON object, or nothing. */
11
+ export declare function serviceData(text: string): Record<string, unknown>;
12
+ declare const _default: import("@sdeck/plugin").PluginDef;
13
+ export default _default;
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.tsx"],"names":[],"mappings":"AAWA,cAAc,aAAa,CAAC;AAoD5B,sFAAsF;AACtF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAI9E;AAED,kEAAkE;AAClE,wBAAgB,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAGjD;AA6BD,eAAO,MAAM,QAAQ,WAAY,MAAM,WAAoD,CAAC;AAyF5F,6DAA6D;AAC7D,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYjE"}
package/dist/index.js ADDED
@@ -0,0 +1,551 @@
1
+ // @bun
2
+ // src/index.tsx
3
+ import {
4
+ defineAction,
5
+ definePlugin,
6
+ defineTrigger,
7
+ ManagedConnection,
8
+ PermanentError as PermanentError2
9
+ } from "@sdeck/plugin";
10
+ import { iconLayer, iconLook, textLayer } from "@sdeck/schema";
11
+
12
+ // src/client.ts
13
+ import { PermanentError } from "@sdeck/plugin";
14
+ function socketUrl(address) {
15
+ const url = new URL(/^[a-z]+:\/\//i.test(address) ? address : `http://${address}`);
16
+ if (!/^(https?|wss?):$/.test(url.protocol))
17
+ throw new Error("use an http or https address");
18
+ url.protocol = /^(https|wss):$/.test(url.protocol) ? "wss:" : "ws:";
19
+ const path = url.pathname.replace(/\/+$/, "").replace(/\/api\/websocket$/, "");
20
+ url.pathname = `${path}/api/websocket`;
21
+ url.search = "";
22
+ url.hash = "";
23
+ return url.toString();
24
+ }
25
+ var toState = (raw) => ({
26
+ state: raw.state,
27
+ name: typeof raw.attributes?.friendly_name === "string" ? raw.attributes.friendly_name : raw.entity_id,
28
+ attributes: raw.attributes ?? {}
29
+ });
30
+ function withEntity(entities, id, state) {
31
+ const dot = id.indexOf(".");
32
+ const domain = id.slice(0, dot);
33
+ const object = id.slice(dot + 1);
34
+ if (dot <= 0 || !object)
35
+ return entities;
36
+ const next = { ...entities[domain] };
37
+ if (state)
38
+ next[object] = state;
39
+ else
40
+ delete next[object];
41
+ return { ...entities, [domain]: next };
42
+ }
43
+ function connectHomeAssistant(address, token, lost, signal, pingMs = 30000) {
44
+ return new Promise((resolve, reject) => {
45
+ let socket;
46
+ try {
47
+ socket = new WebSocket(socketUrl(address));
48
+ } catch {
49
+ reject(new PermanentError(`"${address}" is not a Home Assistant address`));
50
+ return;
51
+ }
52
+ const pending = new Map;
53
+ const listeners = new Set;
54
+ let entities = {};
55
+ let ready = false;
56
+ let next = 1;
57
+ let failure;
58
+ let heartbeat;
59
+ const abort = () => socket.close();
60
+ signal.addEventListener("abort", abort, { once: true });
61
+ const handshake = setTimeout(() => {
62
+ failure = new Error("Home Assistant did not answer");
63
+ socket.close();
64
+ }, 1e4);
65
+ let subscription = 0;
66
+ const command = (message) => new Promise((done, fail) => {
67
+ if (socket.readyState !== WebSocket.OPEN) {
68
+ fail(new Error("Home Assistant is not connected"));
69
+ return;
70
+ }
71
+ const id = next++;
72
+ const timer = setTimeout(() => {
73
+ pending.delete(id);
74
+ fail(new Error(`Home Assistant did not answer ${message.type}`));
75
+ }, 1e4);
76
+ pending.set(id, {
77
+ resolve: (r) => {
78
+ clearTimeout(timer);
79
+ done(r);
80
+ },
81
+ reject: (e) => {
82
+ clearTimeout(timer);
83
+ fail(e);
84
+ }
85
+ });
86
+ socket.send(JSON.stringify({ id, ...message }));
87
+ });
88
+ const client = {
89
+ command,
90
+ entities: () => entities,
91
+ onChange: (listener) => {
92
+ listeners.add(listener);
93
+ return () => void listeners.delete(listener);
94
+ }
95
+ };
96
+ const start = async () => {
97
+ subscription = next;
98
+ const early = [];
99
+ const collect = (change) => {
100
+ const s = change.state;
101
+ if (s)
102
+ early.push({ entity_id: change.entity, state: s.state, attributes: s.attributes });
103
+ };
104
+ listeners.add(collect);
105
+ await command({ type: "subscribe_events", event_type: "state_changed" });
106
+ const states = await command({ type: "get_states" });
107
+ listeners.delete(collect);
108
+ for (const raw of [...states, ...early]) {
109
+ entities = withEntity(entities, raw.entity_id, toState(raw));
110
+ }
111
+ };
112
+ socket.onmessage = (message) => {
113
+ let packet;
114
+ try {
115
+ packet = JSON.parse(String(message.data));
116
+ } catch {
117
+ return;
118
+ }
119
+ switch (packet.type) {
120
+ case "auth_required":
121
+ socket.send(JSON.stringify({ type: "auth", access_token: token }));
122
+ break;
123
+ case "auth_invalid":
124
+ failure = new PermanentError("Home Assistant rejected the access token");
125
+ socket.close();
126
+ break;
127
+ case "auth_ok":
128
+ start().then(() => {
129
+ clearTimeout(handshake);
130
+ ready = true;
131
+ heartbeat = setInterval(() => {
132
+ command({ type: "ping" }).catch(() => socket.close());
133
+ }, pingMs);
134
+ resolve({ value: client, close: () => socket.close() });
135
+ }, (error) => {
136
+ failure = error;
137
+ socket.close();
138
+ });
139
+ break;
140
+ case "pong":
141
+ pending.get(packet.id)?.resolve(undefined);
142
+ pending.delete(packet.id);
143
+ break;
144
+ case "result": {
145
+ const waiter = pending.get(packet.id);
146
+ if (!waiter)
147
+ return;
148
+ pending.delete(packet.id);
149
+ if (packet.success)
150
+ waiter.resolve(packet.result);
151
+ else {
152
+ const error = packet.error;
153
+ waiter.reject(new Error(error?.message ?? "Home Assistant refused the command"));
154
+ }
155
+ break;
156
+ }
157
+ case "event": {
158
+ if (packet.id !== subscription)
159
+ return;
160
+ const data = packet.event?.data;
161
+ const entity = data?.entity_id;
162
+ if (typeof entity !== "string")
163
+ return;
164
+ const raw = data?.new_state;
165
+ const state = raw ? toState(raw) : undefined;
166
+ const from = data?.old_state?.state;
167
+ entities = withEntity(entities, entity, state);
168
+ for (const listener of [...listeners])
169
+ listener({ entity, state, from });
170
+ break;
171
+ }
172
+ }
173
+ };
174
+ socket.onclose = () => {
175
+ clearTimeout(handshake);
176
+ clearInterval(heartbeat);
177
+ signal.removeEventListener("abort", abort);
178
+ const error = failure ?? new Error(ready ? "Home Assistant closed the connection" : `cannot reach ${address}`);
179
+ for (const waiter of [...pending.values()])
180
+ waiter.reject(error);
181
+ pending.clear();
182
+ if (ready)
183
+ lost(error);
184
+ else
185
+ reject(error);
186
+ };
187
+ socket.onerror = () => {};
188
+ });
189
+ }
190
+
191
+ // src/index.tsx
192
+ var context;
193
+ var entityListeners = new Set;
194
+ var changeListeners = new Set;
195
+ var current;
196
+ function publish(entities) {
197
+ current = entities;
198
+ for (const listener of [...entityListeners])
199
+ listener(entities);
200
+ }
201
+ var connection = new ManagedConnection({
202
+ open: async (lost, signal) => {
203
+ const settings = context?.settings() ?? {};
204
+ const address = String(settings.url || "");
205
+ const token = String(settings.token || "");
206
+ if (!address || !token) {
207
+ throw new PermanentError2("Set the address and an access token in the plugin's settings");
208
+ }
209
+ const link = await connectHomeAssistant(address, token, (error) => {
210
+ publish(undefined);
211
+ lost(error);
212
+ }, signal);
213
+ const off = link.value.onChange((change) => {
214
+ publish(link.value.entities());
215
+ context?.emit("state", change);
216
+ for (const listener of [...changeListeners])
217
+ listener(change);
218
+ });
219
+ publish(link.value.entities());
220
+ return {
221
+ value: link.value,
222
+ close: () => {
223
+ off();
224
+ link.close();
225
+ publish(undefined);
226
+ }
227
+ };
228
+ },
229
+ onStatus: (state, error) => {
230
+ if (state === "connected")
231
+ context?.status("Connected to Home Assistant", "ok");
232
+ else if (state === "disconnected") {
233
+ context?.status(error?.message, error ? "error" : "info");
234
+ }
235
+ }
236
+ });
237
+ function splitEntity(entity) {
238
+ const match = /^([a-z0-9_]+)\.([a-z0-9_]+)$/.exec(entity.trim().toLowerCase());
239
+ if (!match)
240
+ throw new Error(`"${entity}" is not an entity id (like light.kitchen)`);
241
+ return { domain: match[1], object: match[2] };
242
+ }
243
+ function entityPath(entity) {
244
+ const [domain = "", object = ""] = entity.trim().toLowerCase().split(".");
245
+ return `ha.entities[${JSON.stringify(domain)}][${JSON.stringify(object)}]`;
246
+ }
247
+ var entityField = {
248
+ type: "text",
249
+ label: "Entity",
250
+ source: "entities",
251
+ placeholder: "light.kitchen"
252
+ };
253
+ var DOMAIN_ICONS = {
254
+ light: { icon: "lucide/lightbulb", off: "lucide/lightbulb-off", on: "on" },
255
+ switch: { icon: "lucide/toggle-right", off: "lucide/toggle-left", on: "on" },
256
+ input_boolean: { icon: "lucide/toggle-right", off: "lucide/toggle-left", on: "on" },
257
+ fan: { icon: "lucide/fan", on: "on" },
258
+ lock: { icon: "lucide/lock", off: "lucide/lock-open", on: "locked" },
259
+ cover: { icon: "lucide/blinds", on: "open" },
260
+ media_player: { icon: "lucide/speaker", on: "playing" },
261
+ climate: { icon: "lucide/thermometer" },
262
+ sensor: { icon: "lucide/gauge" },
263
+ binary_sensor: { icon: "lucide/radar", on: "on" },
264
+ scene: { icon: "lucide/sparkles" },
265
+ script: { icon: "lucide/scroll-text" },
266
+ automation: { icon: "lucide/workflow", on: "on" },
267
+ person: { icon: "lucide/user", on: "home" },
268
+ vacuum: { icon: "lucide/bot", on: "cleaning" }
269
+ };
270
+ var HOME_ICON = { icon: "si/SiHomeassistant", off: undefined, on: undefined };
271
+ var domainOf = (entity) => entity.trim().toLowerCase().split(".")[0] ?? "";
272
+ var READINGS = new Set(["sensor", "climate", "person", "media_player"]);
273
+ var entityLook = (entity, title, background) => {
274
+ const path = entityPath(entity);
275
+ const domain = domainOf(entity);
276
+ const { icon, off, on } = DOMAIN_ICONS[domain] ?? HOME_ICON;
277
+ const lit = on ? `${path}.state == ${JSON.stringify(on)}` : "true";
278
+ const reading = READINGS.has(domain);
279
+ const name = title || `{{${path}.name ?? ${JSON.stringify(entity || "Entity")}}}`;
280
+ return {
281
+ background,
282
+ layers: [
283
+ iconLayer("on", icon, {
284
+ color: on ? "#fbbf24" : "#ffffff",
285
+ size: 48,
286
+ position: "top",
287
+ visible: lit
288
+ }),
289
+ iconLayer("off", off ?? icon, {
290
+ color: "#6b7280",
291
+ size: 48,
292
+ position: "top",
293
+ visible: `!(${lit})`
294
+ }),
295
+ textLayer("label", reading ? `{{${path}.state ?? "N/A"}}{{${path}.attributes.unit_of_measurement ?? ""}}` : name, { size: reading ? 17 : 12, position: "bottom" })
296
+ ]
297
+ };
298
+ };
299
+ var OPERATIONS = [
300
+ { value: "toggle", label: "Toggle" },
301
+ { value: "turn_on", label: "Turn on" },
302
+ { value: "turn_off", label: "Turn off" }
303
+ ];
304
+ var entity = defineAction({
305
+ id: "entity",
306
+ name: "Entity",
307
+ description: "Shows an entity's state; pressing it toggles it or turns it on or off.",
308
+ category: "Home Assistant",
309
+ icon: "house",
310
+ slots: ["key", "sensor", "window"],
311
+ settings: {
312
+ entity: entityField,
313
+ operation: { type: "select", label: "When pressed", default: "toggle", options: OPERATIONS },
314
+ text: {
315
+ type: "text",
316
+ label: "Title",
317
+ placeholder: "Defaults to the entity's name",
318
+ appearance: true
319
+ },
320
+ background: { type: "color", label: "Background", default: "#111827", appearance: true }
321
+ },
322
+ run: async ({ settings }) => {
323
+ const { domain, object } = splitEntity(settings.entity);
324
+ const entity_id = `${domain}.${object}`;
325
+ const call = (ha, service) => ha.command({
326
+ type: "call_service",
327
+ domain: "homeassistant",
328
+ service,
329
+ target: { entity_id }
330
+ });
331
+ return connection.with(async (ha) => {
332
+ const before = ha.entities()[domain]?.[object]?.state;
333
+ if (before === undefined)
334
+ throw new Error(`no entity ${entity_id}`);
335
+ await call(ha, settings.operation);
336
+ const restore = before === "on" ? "turn_on" : before === "off" ? "turn_off" : undefined;
337
+ return {
338
+ label: `${settings.operation} ${entity_id}`,
339
+ ...restore && {
340
+ undo: () => connection.with((again) => call(again, restore))
341
+ }
342
+ };
343
+ });
344
+ },
345
+ look: (s) => entityLook(s.entity, s.text, s.background)
346
+ });
347
+ function serviceData(text) {
348
+ if (!text.trim())
349
+ return {};
350
+ let value;
351
+ try {
352
+ value = JSON.parse(text);
353
+ } catch {
354
+ throw new Error("the data is not valid JSON");
355
+ }
356
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
357
+ throw new Error("the data must be a JSON object");
358
+ }
359
+ return value;
360
+ }
361
+ var service = defineAction({
362
+ id: "service",
363
+ name: "Call a service",
364
+ description: "Calls any Home Assistant service, e.g. scene.turn_on or light.turn_on.",
365
+ category: "Home Assistant",
366
+ icon: "wand-sparkles",
367
+ slots: ["key", "sensor"],
368
+ settings: {
369
+ service: {
370
+ type: "text",
371
+ label: "Service",
372
+ source: "services",
373
+ placeholder: "light.turn_on"
374
+ },
375
+ entity: { ...entityField, description: "Leave empty for services without a target." },
376
+ data: {
377
+ type: "text",
378
+ label: "Data (JSON)",
379
+ multiline: true,
380
+ placeholder: '{ "brightness_pct": 40 }'
381
+ },
382
+ text: { type: "text", label: "Text", placeholder: "Defaults to the service", appearance: true },
383
+ background: { type: "color", label: "Background", default: "#0c4a6e", appearance: true }
384
+ },
385
+ run: async ({ settings }) => {
386
+ const { domain, object } = splitEntity(settings.service);
387
+ const data = serviceData(settings.data);
388
+ await connection.with((ha) => ha.command({
389
+ type: "call_service",
390
+ domain,
391
+ service: object,
392
+ service_data: data,
393
+ ...settings.entity && { target: { entity_id: settings.entity.trim() } }
394
+ }));
395
+ return { label: `${settings.service} ${settings.entity}`.trim() };
396
+ },
397
+ look: (s) => iconLook({
398
+ icon: DOMAIN_ICONS[domainOf(s.service)]?.icon ?? "lucide/wand-sparkles",
399
+ background: s.background,
400
+ caption: s.text || s.service.split(".")[1]?.replace(/_/g, " ") || ""
401
+ })
402
+ });
403
+ var stateChanged = defineTrigger({
404
+ id: "state-changed",
405
+ name: "When a Home Assistant entity changes",
406
+ settings: {
407
+ entity: entityField,
408
+ to: { type: "text", label: "To the state", placeholder: "Any state" }
409
+ },
410
+ subscribe: ({ settings, fire }) => {
411
+ const { domain, object } = splitEntity(settings.entity);
412
+ const wanted = `${domain}.${object}`;
413
+ const listener = (change) => {
414
+ if (change.entity !== wanted)
415
+ return;
416
+ const state = change.state?.state;
417
+ if (state === change.from)
418
+ return;
419
+ if (!settings.to || state === settings.to.trim()) {
420
+ fire({ entity: wanted, state, from: change.from });
421
+ }
422
+ };
423
+ changeListeners.add(listener);
424
+ const release = connection.hold();
425
+ return () => {
426
+ changeListeners.delete(listener);
427
+ release();
428
+ };
429
+ }
430
+ });
431
+ var src_default = definePlugin({
432
+ id: "@sdeck/plugin-home-assistant",
433
+ name: "Home Assistant",
434
+ version: "0.2.0",
435
+ namespace: "ha",
436
+ description: "Entity states and service calls over Home Assistant's WebSocket API.",
437
+ author: "sdeck",
438
+ permissions: ["network"],
439
+ settings: {
440
+ url: { type: "text", label: "Address", placeholder: "http://homeassistant.local:8123" },
441
+ token: {
442
+ type: "secret",
443
+ label: "Access token",
444
+ description: "A long-lived access token from your Home Assistant profile."
445
+ }
446
+ },
447
+ onboarding: {
448
+ steps: [
449
+ {
450
+ id: "token",
451
+ title: "Connect to Home Assistant",
452
+ body: "Enter the address you open Home Assistant at. For the token, open your **profile** in Home Assistant, then **Security \u2192 Long-lived access tokens \u2192 Create token**.",
453
+ link: {
454
+ label: "About access tokens",
455
+ url: "https://www.home-assistant.io/docs/authentication/#your-account-profile"
456
+ },
457
+ settings: ["url", "token"]
458
+ },
459
+ {
460
+ id: "connect",
461
+ title: "Test the connection",
462
+ command: "connect"
463
+ }
464
+ ],
465
+ starterPage: false
466
+ },
467
+ commands: [
468
+ {
469
+ id: "connect",
470
+ name: "Test the connection",
471
+ run: async () => {
472
+ connection.restart();
473
+ await connection.with(() => {});
474
+ }
475
+ }
476
+ ],
477
+ actions: [entity, service],
478
+ triggers: [stateChanged],
479
+ optionSources: {
480
+ entities: () => connection.with((ha) => Object.entries(ha.entities()).flatMap(([domain, objects]) => Object.entries(objects).map(([object, e]) => ({
481
+ value: `${domain}.${object}`,
482
+ label: e.name
483
+ }))).sort((a, b) => a.value.localeCompare(b.value))),
484
+ services: () => connection.with(async (ha) => {
485
+ const services = await ha.command({ type: "get_services" });
486
+ return Object.entries(services).flatMap(([domain, names]) => Object.keys(names).map((name) => `${domain}.${name}`)).sort().map((value) => ({ value, label: value }));
487
+ })
488
+ },
489
+ state: [
490
+ {
491
+ id: "entities",
492
+ name: "Entities",
493
+ type: "json",
494
+ description: "ha.entities.light.kitchen.state, .name, .attributes",
495
+ start: (set) => {
496
+ const listener = (entities) => set(entities);
497
+ entityListeners.add(listener);
498
+ listener(current);
499
+ const release = connection.hold();
500
+ return () => {
501
+ entityListeners.delete(listener);
502
+ release();
503
+ };
504
+ }
505
+ },
506
+ {
507
+ id: "connected",
508
+ name: "Connected",
509
+ type: "boolean",
510
+ start: (set) => {
511
+ const listener = (entities) => set(entities !== undefined);
512
+ entityListeners.add(listener);
513
+ listener(current);
514
+ const release = connection.hold();
515
+ return () => {
516
+ entityListeners.delete(listener);
517
+ release();
518
+ };
519
+ }
520
+ }
521
+ ],
522
+ activate(activated) {
523
+ context = activated;
524
+ let settings = JSON.stringify(activated.settings());
525
+ const off = activated.onSettings(() => {
526
+ const next = JSON.stringify(activated.settings());
527
+ if (next === settings)
528
+ return;
529
+ settings = next;
530
+ connection.restart();
531
+ });
532
+ return () => {
533
+ off();
534
+ connection.close();
535
+ publish(undefined);
536
+ context = undefined;
537
+ };
538
+ }
539
+ });
540
+ export {
541
+ connectHomeAssistant,
542
+ src_default as default,
543
+ domainOf,
544
+ entityPath,
545
+ serviceData,
546
+ socketUrl,
547
+ splitEntity,
548
+ withEntity
549
+ };
550
+
551
+ //# debugId=470095898C1AB1BC64756E2164756E21