@sdeck/plugin-home-assistant 0.0.0-stage → 0.1.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/client.d.ts +33 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1308 -0
- package/dist/index.js.map +21 -0
- package/package.json +60 -4
- package/src/client.ts +231 -0
- package/src/index.tsx +399 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1308 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// ../core/src/element.ts
|
|
3
|
+
var runtime;
|
|
4
|
+
function registerElementRuntime(next) {
|
|
5
|
+
runtime = next;
|
|
6
|
+
}
|
|
7
|
+
// ../react/src/render.ts
|
|
8
|
+
function isReactElement(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && "$$typeof" in value;
|
|
10
|
+
}
|
|
11
|
+
var defaultRenderer = {};
|
|
12
|
+
var fontRenderers = new WeakMap;
|
|
13
|
+
async function createRenderer(fonts) {
|
|
14
|
+
const { Renderer } = await import("@takumi-rs/core");
|
|
15
|
+
const renderer = new Renderer;
|
|
16
|
+
for (const font of fonts) {
|
|
17
|
+
await renderer.registerFont({
|
|
18
|
+
name: font.name,
|
|
19
|
+
data: font.data,
|
|
20
|
+
...font.weight !== undefined && { weight: font.weight },
|
|
21
|
+
...font.style !== undefined && { style: font.style }
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
return renderer;
|
|
25
|
+
}
|
|
26
|
+
function getRenderer(fonts) {
|
|
27
|
+
if (!fonts?.length) {
|
|
28
|
+
defaultRenderer.current ??= createRenderer([]);
|
|
29
|
+
defaultRenderer.current.catch(() => {
|
|
30
|
+
defaultRenderer.current = undefined;
|
|
31
|
+
});
|
|
32
|
+
return defaultRenderer.current;
|
|
33
|
+
}
|
|
34
|
+
let renderer = fontRenderers.get(fonts);
|
|
35
|
+
if (!renderer) {
|
|
36
|
+
renderer = createRenderer(fonts);
|
|
37
|
+
renderer.catch(() => fontRenderers.delete(fonts));
|
|
38
|
+
fontRenderers.set(fonts, renderer);
|
|
39
|
+
}
|
|
40
|
+
return renderer;
|
|
41
|
+
}
|
|
42
|
+
var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
43
|
+
function toNode(node, text = true) {
|
|
44
|
+
if ("text" in node) {
|
|
45
|
+
return text ? { type: "text", text: node.text } : { type: "container", children: [] };
|
|
46
|
+
}
|
|
47
|
+
const { style, tw, src, width, height } = node.props;
|
|
48
|
+
const common = {
|
|
49
|
+
...typeof tw === "string" && { tw }
|
|
50
|
+
};
|
|
51
|
+
if (node.type === "img") {
|
|
52
|
+
if (typeof src !== "string")
|
|
53
|
+
throw new Error("<img> needs a string `src` (URL or data: URI)");
|
|
54
|
+
return {
|
|
55
|
+
type: "image",
|
|
56
|
+
src,
|
|
57
|
+
...number(width) !== undefined && { width: number(width) },
|
|
58
|
+
...number(height) !== undefined && { height: number(height) },
|
|
59
|
+
...typeof style === "object" && style !== null && { style },
|
|
60
|
+
...common
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
type: "container",
|
|
65
|
+
style: { display: "flex", ...typeof style === "object" ? style : {} },
|
|
66
|
+
children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
|
|
67
|
+
...common
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
var reconciler;
|
|
71
|
+
var flushing = 0;
|
|
72
|
+
function flushAll(renderer) {
|
|
73
|
+
flushing++;
|
|
74
|
+
try {
|
|
75
|
+
renderer.flushSyncWork();
|
|
76
|
+
for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
|
|
77
|
+
renderer.flushSyncWork();
|
|
78
|
+
} finally {
|
|
79
|
+
flushing--;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function loadReconciler() {
|
|
83
|
+
reconciler ??= (async () => {
|
|
84
|
+
let factoryModule;
|
|
85
|
+
let constants;
|
|
86
|
+
let React;
|
|
87
|
+
try {
|
|
88
|
+
[factoryModule, constants, React] = await Promise.all([
|
|
89
|
+
import("react-reconciler"),
|
|
90
|
+
import("react-reconciler/constants.js"),
|
|
91
|
+
import("react")
|
|
92
|
+
]);
|
|
93
|
+
} catch (cause) {
|
|
94
|
+
throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
|
|
95
|
+
cause
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
let priority = constants.NoEventPriority;
|
|
99
|
+
const noop = () => {};
|
|
100
|
+
const hostConfig = {
|
|
101
|
+
supportsMutation: true,
|
|
102
|
+
supportsPersistence: false,
|
|
103
|
+
supportsHydration: false,
|
|
104
|
+
isPrimaryRenderer: true,
|
|
105
|
+
warnsIfNotActing: false,
|
|
106
|
+
noTimeout: -1,
|
|
107
|
+
scheduleTimeout: setTimeout,
|
|
108
|
+
cancelTimeout: clearTimeout,
|
|
109
|
+
supportsMicrotasks: true,
|
|
110
|
+
scheduleMicrotask: queueMicrotask,
|
|
111
|
+
createInstance: (type, props) => {
|
|
112
|
+
const { children: _children, ...rest } = props;
|
|
113
|
+
return { type, props: rest, children: [] };
|
|
114
|
+
},
|
|
115
|
+
createTextInstance: (text) => ({ text }),
|
|
116
|
+
shouldSetTextContent: () => false,
|
|
117
|
+
appendInitialChild: (parent, child) => parent.children.push(child),
|
|
118
|
+
appendChild: (parent, child) => parent.children.push(child),
|
|
119
|
+
appendChildToContainer: (container, child) => container.children.push(child),
|
|
120
|
+
insertBefore: (parent, child, before) => {
|
|
121
|
+
const children = parent.children;
|
|
122
|
+
const existing = children.indexOf(child);
|
|
123
|
+
if (existing !== -1)
|
|
124
|
+
children.splice(existing, 1);
|
|
125
|
+
children.splice(children.indexOf(before), 0, child);
|
|
126
|
+
},
|
|
127
|
+
insertInContainerBefore: (container, child, before) => {
|
|
128
|
+
const children = container.children;
|
|
129
|
+
const existing = children.indexOf(child);
|
|
130
|
+
if (existing !== -1)
|
|
131
|
+
children.splice(existing, 1);
|
|
132
|
+
children.splice(children.indexOf(before), 0, child);
|
|
133
|
+
},
|
|
134
|
+
removeChild: (parent, child) => {
|
|
135
|
+
parent.children.splice(parent.children.indexOf(child), 1);
|
|
136
|
+
},
|
|
137
|
+
removeChildFromContainer: (container, child) => {
|
|
138
|
+
container.children.splice(container.children.indexOf(child), 1);
|
|
139
|
+
},
|
|
140
|
+
clearContainer: (container) => {
|
|
141
|
+
container.children = [];
|
|
142
|
+
},
|
|
143
|
+
commitUpdate: (instance, _type, _prev, next) => {
|
|
144
|
+
const { children: _children, ...rest } = next;
|
|
145
|
+
instance.props = rest;
|
|
146
|
+
},
|
|
147
|
+
commitTextUpdate: (text, _old, next) => {
|
|
148
|
+
text.text = next;
|
|
149
|
+
},
|
|
150
|
+
finalizeInitialChildren: () => false,
|
|
151
|
+
getPublicInstance: (instance) => instance,
|
|
152
|
+
getRootHostContext: () => ({}),
|
|
153
|
+
getChildHostContext: (parent) => parent,
|
|
154
|
+
prepareForCommit: () => null,
|
|
155
|
+
resetAfterCommit: (container) => container.onCommit(),
|
|
156
|
+
preparePortalMount: noop,
|
|
157
|
+
detachDeletedInstance: noop,
|
|
158
|
+
hideInstance: noop,
|
|
159
|
+
unhideInstance: noop,
|
|
160
|
+
hideTextInstance: noop,
|
|
161
|
+
unhideTextInstance: noop,
|
|
162
|
+
getInstanceFromNode: () => null,
|
|
163
|
+
beforeActiveInstanceBlur: noop,
|
|
164
|
+
afterActiveInstanceBlur: noop,
|
|
165
|
+
prepareScopeUpdate: noop,
|
|
166
|
+
getInstanceFromScope: () => null,
|
|
167
|
+
bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
|
|
168
|
+
extraDevToolsConfig: null,
|
|
169
|
+
rendererVersion: "0.0.0",
|
|
170
|
+
rendererPackageName: "sdeck",
|
|
171
|
+
getCurrentUpdatePriority: () => priority,
|
|
172
|
+
setCurrentUpdatePriority: (next) => {
|
|
173
|
+
priority = next;
|
|
174
|
+
},
|
|
175
|
+
resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
|
|
176
|
+
resolveEventType: () => null,
|
|
177
|
+
resolveEventTimeStamp: () => -1.1,
|
|
178
|
+
shouldAttemptEagerTransition: () => false,
|
|
179
|
+
trackSchedulerEvent: noop,
|
|
180
|
+
requestPostPaintCallback: noop,
|
|
181
|
+
maySuspendCommit: () => false,
|
|
182
|
+
preloadInstance: () => true,
|
|
183
|
+
startSuspendingCommit: noop,
|
|
184
|
+
suspendInstance: noop,
|
|
185
|
+
waitForCommitToBeReady: () => null,
|
|
186
|
+
getSuspendedCommitReason: () => null,
|
|
187
|
+
NotPendingTransition: null,
|
|
188
|
+
HostTransitionContext: React.createContext(null),
|
|
189
|
+
resetFormInstance: noop
|
|
190
|
+
};
|
|
191
|
+
const factory = factoryModule.default ?? factoryModule;
|
|
192
|
+
return factory(hostConfig);
|
|
193
|
+
})();
|
|
194
|
+
reconciler.catch(() => {
|
|
195
|
+
reconciler = undefined;
|
|
196
|
+
});
|
|
197
|
+
return reconciler;
|
|
198
|
+
}
|
|
199
|
+
function noopIndicator() {}
|
|
200
|
+
async function createReactRoot(size, onFrame, options = {}) {
|
|
201
|
+
const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
|
|
202
|
+
let dirty = false;
|
|
203
|
+
let drawing;
|
|
204
|
+
let lastTree;
|
|
205
|
+
let unmounted = false;
|
|
206
|
+
let renderError;
|
|
207
|
+
let initial = true;
|
|
208
|
+
const fail = (error) => {
|
|
209
|
+
if (initial)
|
|
210
|
+
renderError ??= { error };
|
|
211
|
+
else
|
|
212
|
+
(options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
|
|
213
|
+
};
|
|
214
|
+
async function draw() {
|
|
215
|
+
await Promise.resolve();
|
|
216
|
+
while (dirty && !unmounted) {
|
|
217
|
+
dirty = false;
|
|
218
|
+
try {
|
|
219
|
+
const [root] = container.children;
|
|
220
|
+
if (!root)
|
|
221
|
+
continue;
|
|
222
|
+
const tree = toNode(root, options.text !== false);
|
|
223
|
+
const key = JSON.stringify(tree);
|
|
224
|
+
if (key === lastTree)
|
|
225
|
+
continue;
|
|
226
|
+
lastTree = key;
|
|
227
|
+
const pixels = await takumi.render(tree, {
|
|
228
|
+
width: size.width,
|
|
229
|
+
height: size.height,
|
|
230
|
+
format: "raw",
|
|
231
|
+
...options.scale !== undefined && { devicePixelRatio: options.scale }
|
|
232
|
+
});
|
|
233
|
+
await onFrame({
|
|
234
|
+
data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
|
|
235
|
+
width: size.width,
|
|
236
|
+
height: size.height,
|
|
237
|
+
channels: 4
|
|
238
|
+
});
|
|
239
|
+
} catch (error) {
|
|
240
|
+
lastTree = undefined;
|
|
241
|
+
fail(error);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
drawing = undefined;
|
|
245
|
+
}
|
|
246
|
+
const container = {
|
|
247
|
+
children: [],
|
|
248
|
+
onCommit() {
|
|
249
|
+
dirty = true;
|
|
250
|
+
drawing ??= draw();
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
const onError = (error) => fail(error);
|
|
254
|
+
const onCaughtError = () => {};
|
|
255
|
+
const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
|
|
256
|
+
const flush = () => flushAll(renderer);
|
|
257
|
+
const handle = {
|
|
258
|
+
render(element) {
|
|
259
|
+
if (unmounted)
|
|
260
|
+
throw new Error("This React root was unmounted");
|
|
261
|
+
renderer.updateContainerSync(element, root, null, null);
|
|
262
|
+
flush();
|
|
263
|
+
},
|
|
264
|
+
async idle() {
|
|
265
|
+
while (drawing)
|
|
266
|
+
await drawing;
|
|
267
|
+
if (initial && renderError) {
|
|
268
|
+
const { error } = renderError;
|
|
269
|
+
renderError = undefined;
|
|
270
|
+
throw error;
|
|
271
|
+
}
|
|
272
|
+
initial = false;
|
|
273
|
+
},
|
|
274
|
+
async unmount() {
|
|
275
|
+
if (unmounted)
|
|
276
|
+
return;
|
|
277
|
+
renderer.updateContainerSync(null, root, null, null);
|
|
278
|
+
flush();
|
|
279
|
+
unmounted = true;
|
|
280
|
+
await drawing;
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
return handle;
|
|
284
|
+
}
|
|
285
|
+
async function renderReact(element, size, fonts, scale) {
|
|
286
|
+
let frame;
|
|
287
|
+
const root = await createReactRoot(size, (next) => {
|
|
288
|
+
frame = next;
|
|
289
|
+
}, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
|
|
290
|
+
try {
|
|
291
|
+
root.render(element);
|
|
292
|
+
await root.idle();
|
|
293
|
+
} finally {
|
|
294
|
+
await root.unmount();
|
|
295
|
+
}
|
|
296
|
+
if (!frame)
|
|
297
|
+
throw new Error("React element rendered nothing");
|
|
298
|
+
return frame;
|
|
299
|
+
}
|
|
300
|
+
registerElementRuntime({
|
|
301
|
+
matches: isReactElement,
|
|
302
|
+
render: (element, size, options) => renderReact(element, size, options?.fonts),
|
|
303
|
+
createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
|
|
304
|
+
});
|
|
305
|
+
// ../app/src/app.tsx
|
|
306
|
+
import { Fragment, useSyncExternalStore } from "react";
|
|
307
|
+
|
|
308
|
+
// ../app/src/context.ts
|
|
309
|
+
import { createContext, useContext } from "react";
|
|
310
|
+
var DeckContext = createContext(undefined);
|
|
311
|
+
var SlotContext = createContext(undefined);
|
|
312
|
+
var NavigatorContext = createContext(undefined);
|
|
313
|
+
// ../app/src/hooks.ts
|
|
314
|
+
import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
|
|
315
|
+
|
|
316
|
+
// ../app/src/swipe.ts
|
|
317
|
+
var trackers = new WeakMap;
|
|
318
|
+
// ../schema/src/layers.ts
|
|
319
|
+
function iconLayer(id, icon, options = {}) {
|
|
320
|
+
const { color, size = 52, position = "middle", visible, row, frame } = options;
|
|
321
|
+
const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
|
|
322
|
+
return {
|
|
323
|
+
id,
|
|
324
|
+
type: "image",
|
|
325
|
+
src,
|
|
326
|
+
size,
|
|
327
|
+
position,
|
|
328
|
+
...color && { color },
|
|
329
|
+
...visible && { visible },
|
|
330
|
+
...row && { row },
|
|
331
|
+
...frame && { frame }
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function iconLook(options) {
|
|
335
|
+
const { icon, background, caption = "", color = "#ffffff" } = options;
|
|
336
|
+
return {
|
|
337
|
+
background,
|
|
338
|
+
layers: [
|
|
339
|
+
iconLayer("icon", icon, {
|
|
340
|
+
color,
|
|
341
|
+
size: caption ? 46 : 58,
|
|
342
|
+
position: caption ? "top" : "middle"
|
|
343
|
+
}),
|
|
344
|
+
...caption ? [textLayer("label", caption, { color, size: 13, position: "bottom" })] : []
|
|
345
|
+
]
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function textLayer(id, text, options = {}) {
|
|
349
|
+
const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
|
|
350
|
+
const { visible, row, frame } = options;
|
|
351
|
+
return {
|
|
352
|
+
id,
|
|
353
|
+
type: "text",
|
|
354
|
+
text,
|
|
355
|
+
color,
|
|
356
|
+
size,
|
|
357
|
+
weight,
|
|
358
|
+
position,
|
|
359
|
+
...visible && { visible },
|
|
360
|
+
...row && { row },
|
|
361
|
+
...frame && { frame }
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
// ../plugin/src/connection.ts
|
|
365
|
+
class PermanentError extends Error {
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
class ManagedConnection {
|
|
369
|
+
#options;
|
|
370
|
+
#waiters = new Set;
|
|
371
|
+
#holders = 0;
|
|
372
|
+
#link;
|
|
373
|
+
#attempt;
|
|
374
|
+
#retry;
|
|
375
|
+
#linger;
|
|
376
|
+
#delay;
|
|
377
|
+
#failed;
|
|
378
|
+
constructor(options) {
|
|
379
|
+
this.#options = options;
|
|
380
|
+
this.#delay = options.retry?.minMs ?? 1000;
|
|
381
|
+
}
|
|
382
|
+
get current() {
|
|
383
|
+
return this.#link?.value;
|
|
384
|
+
}
|
|
385
|
+
hold() {
|
|
386
|
+
this.#holders++;
|
|
387
|
+
clearTimeout(this.#linger);
|
|
388
|
+
this.#connect();
|
|
389
|
+
let released = false;
|
|
390
|
+
return () => {
|
|
391
|
+
if (released)
|
|
392
|
+
return;
|
|
393
|
+
released = true;
|
|
394
|
+
this.#holders--;
|
|
395
|
+
if (this.#holders > 0)
|
|
396
|
+
return;
|
|
397
|
+
this.#linger = setTimeout(() => this.#drop(), this.#options.lingerMs ?? 3000);
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
async with(use, timeoutMs = 5000) {
|
|
401
|
+
const release = this.hold();
|
|
402
|
+
try {
|
|
403
|
+
return await use(await this.#ready(timeoutMs));
|
|
404
|
+
} finally {
|
|
405
|
+
release();
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
restart() {
|
|
409
|
+
this.#failed = undefined;
|
|
410
|
+
this.#delay = this.#options.retry?.minMs ?? 1000;
|
|
411
|
+
this.#drop();
|
|
412
|
+
if (this.#holders > 0)
|
|
413
|
+
this.#connect();
|
|
414
|
+
}
|
|
415
|
+
close() {
|
|
416
|
+
this.#holders = 0;
|
|
417
|
+
clearTimeout(this.#linger);
|
|
418
|
+
this.#drop();
|
|
419
|
+
this.#reject(new Error("the connection was closed"));
|
|
420
|
+
}
|
|
421
|
+
#ready(timeoutMs) {
|
|
422
|
+
if (this.#link)
|
|
423
|
+
return Promise.resolve(this.#link.value);
|
|
424
|
+
if (this.#failed)
|
|
425
|
+
return Promise.reject(this.#failed);
|
|
426
|
+
if (this.#retry) {
|
|
427
|
+
clearTimeout(this.#retry);
|
|
428
|
+
this.#retry = undefined;
|
|
429
|
+
this.#connect();
|
|
430
|
+
}
|
|
431
|
+
return new Promise((resolve, reject) => {
|
|
432
|
+
let last;
|
|
433
|
+
const waiter = {
|
|
434
|
+
resolve: (value) => {
|
|
435
|
+
clearTimeout(timer);
|
|
436
|
+
resolve(value);
|
|
437
|
+
},
|
|
438
|
+
reject: (error) => {
|
|
439
|
+
last = error;
|
|
440
|
+
clearTimeout(timer);
|
|
441
|
+
this.#waiters.delete(waiter);
|
|
442
|
+
reject(last);
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
const timer = setTimeout(() => waiter.reject(new Error("could not connect in time")), timeoutMs);
|
|
446
|
+
this.#waiters.add(waiter);
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
#connect() {
|
|
450
|
+
if (this.#link || this.#attempt || this.#retry || this.#failed)
|
|
451
|
+
return;
|
|
452
|
+
const attempt = new AbortController;
|
|
453
|
+
this.#attempt = attempt;
|
|
454
|
+
this.#options.onStatus?.("connecting");
|
|
455
|
+
let lostEarly;
|
|
456
|
+
let link;
|
|
457
|
+
const lost = (error) => {
|
|
458
|
+
if (!link) {
|
|
459
|
+
lostEarly = error;
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (this.#link !== link)
|
|
463
|
+
return;
|
|
464
|
+
this.#link = undefined;
|
|
465
|
+
link.close();
|
|
466
|
+
this.#options.onStatus?.("disconnected", error);
|
|
467
|
+
this.#schedule(error);
|
|
468
|
+
};
|
|
469
|
+
const open = async () => {
|
|
470
|
+
const opened = await this.#options.open(lost, attempt.signal);
|
|
471
|
+
if (attempt.signal.aborted) {
|
|
472
|
+
opened.close();
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (lostEarly) {
|
|
476
|
+
opened.close();
|
|
477
|
+
throw lostEarly;
|
|
478
|
+
}
|
|
479
|
+
link = opened;
|
|
480
|
+
this.#attempt = undefined;
|
|
481
|
+
this.#link = opened;
|
|
482
|
+
this.#delay = this.#options.retry?.minMs ?? 1000;
|
|
483
|
+
this.#options.onStatus?.("connected");
|
|
484
|
+
for (const waiter of this.#waiters)
|
|
485
|
+
waiter.resolve(opened.value);
|
|
486
|
+
this.#waiters.clear();
|
|
487
|
+
};
|
|
488
|
+
open().catch((error) => {
|
|
489
|
+
if (attempt.signal.aborted || this.#attempt !== attempt)
|
|
490
|
+
return;
|
|
491
|
+
this.#attempt = undefined;
|
|
492
|
+
this.#options.onStatus?.("disconnected", error);
|
|
493
|
+
this.#reject(error);
|
|
494
|
+
this.#schedule(error);
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
#schedule(error) {
|
|
498
|
+
if (error instanceof PermanentError) {
|
|
499
|
+
this.#failed = error;
|
|
500
|
+
this.#reject(error);
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (this.#holders <= 0)
|
|
504
|
+
return;
|
|
505
|
+
clearTimeout(this.#retry);
|
|
506
|
+
this.#retry = setTimeout(() => {
|
|
507
|
+
this.#retry = undefined;
|
|
508
|
+
if (this.#holders > 0)
|
|
509
|
+
this.#connect();
|
|
510
|
+
}, this.#delay);
|
|
511
|
+
this.#delay = Math.min(this.#delay * 2, this.#options.retry?.maxMs ?? 30000);
|
|
512
|
+
}
|
|
513
|
+
#reject(error) {
|
|
514
|
+
for (const waiter of [...this.#waiters])
|
|
515
|
+
waiter.reject(error);
|
|
516
|
+
this.#waiters.clear();
|
|
517
|
+
}
|
|
518
|
+
#drop() {
|
|
519
|
+
clearTimeout(this.#retry);
|
|
520
|
+
this.#retry = undefined;
|
|
521
|
+
this.#attempt?.abort();
|
|
522
|
+
this.#attempt = undefined;
|
|
523
|
+
const link = this.#link;
|
|
524
|
+
this.#link = undefined;
|
|
525
|
+
if (!link)
|
|
526
|
+
return;
|
|
527
|
+
link.close();
|
|
528
|
+
this.#options.onStatus?.("disconnected");
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
// ../plugin/src/settings.ts
|
|
532
|
+
function checkSchema(schema, sources = {}) {
|
|
533
|
+
const problems = [];
|
|
534
|
+
const types = new Set([
|
|
535
|
+
"text",
|
|
536
|
+
"number",
|
|
537
|
+
"boolean",
|
|
538
|
+
"color",
|
|
539
|
+
"select",
|
|
540
|
+
"page",
|
|
541
|
+
"image",
|
|
542
|
+
"secret"
|
|
543
|
+
]);
|
|
544
|
+
for (const [key, field] of Object.entries(schema)) {
|
|
545
|
+
if (!field || typeof field !== "object" || !types.has(field.type)) {
|
|
546
|
+
problems.push(`setting "${key}" has an unknown type`);
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
if (typeof field.label !== "string")
|
|
550
|
+
problems.push(`setting "${key}" needs a label`);
|
|
551
|
+
const source = "source" in field ? field.source : undefined;
|
|
552
|
+
if (source !== undefined && !(source in sources)) {
|
|
553
|
+
problems.push(`setting "${key}" uses unknown option source "${source}"`);
|
|
554
|
+
}
|
|
555
|
+
if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
|
|
556
|
+
problems.push(`setting "${key}" needs at least one option or a source`);
|
|
557
|
+
}
|
|
558
|
+
for (const other of "dependsOn" in field && field.dependsOn || []) {
|
|
559
|
+
if (!(other in schema))
|
|
560
|
+
problems.push(`setting "${key}" depends on unknown "${other}"`);
|
|
561
|
+
}
|
|
562
|
+
if (field.visibleIf !== undefined) {
|
|
563
|
+
for (const other of Object.keys(field.visibleIf)) {
|
|
564
|
+
if (!(other in schema))
|
|
565
|
+
problems.push(`setting "${key}" depends on unknown "${other}"`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return problems;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
// ../plugin/src/plugin.ts
|
|
573
|
+
var PERMISSIONS = [
|
|
574
|
+
"shell",
|
|
575
|
+
"process",
|
|
576
|
+
"filesystem",
|
|
577
|
+
"network",
|
|
578
|
+
"input",
|
|
579
|
+
"audio",
|
|
580
|
+
"clipboard"
|
|
581
|
+
];
|
|
582
|
+
var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
|
|
583
|
+
var NAMESPACE = /^[a-z][\w-]{0,31}$/;
|
|
584
|
+
var LOCAL_ID = /^[\w.-]+$/;
|
|
585
|
+
function defineAction(def) {
|
|
586
|
+
return {
|
|
587
|
+
...def,
|
|
588
|
+
slots: def.slots ?? ["key"],
|
|
589
|
+
settings: def.settings ?? {}
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
function defineTrigger(def) {
|
|
593
|
+
return { ...def, settings: def.settings ?? {} };
|
|
594
|
+
}
|
|
595
|
+
function definePlugin(def) {
|
|
596
|
+
const problems = checkPlugin(def);
|
|
597
|
+
if (problems.length > 0) {
|
|
598
|
+
throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
|
|
599
|
+
}
|
|
600
|
+
return def;
|
|
601
|
+
}
|
|
602
|
+
function checkLocalIds(kind, items, problems) {
|
|
603
|
+
const seen = new Set;
|
|
604
|
+
for (const item of items) {
|
|
605
|
+
const name = typeof item?.id === "string" ? item.id : "?";
|
|
606
|
+
if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
|
|
607
|
+
problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
|
|
608
|
+
} else if (seen.has(item.id)) {
|
|
609
|
+
problems.push(`${kind} "${name}" is defined twice`);
|
|
610
|
+
}
|
|
611
|
+
seen.add(name);
|
|
612
|
+
}
|
|
613
|
+
return seen;
|
|
614
|
+
}
|
|
615
|
+
function checkPlugin(value) {
|
|
616
|
+
if (!value || typeof value !== "object")
|
|
617
|
+
return ["not an object"];
|
|
618
|
+
const def = value;
|
|
619
|
+
const problems = [];
|
|
620
|
+
if (typeof def.id !== "string" || !ID.test(def.id)) {
|
|
621
|
+
problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
|
|
622
|
+
}
|
|
623
|
+
if (typeof def.name !== "string" || def.name === "")
|
|
624
|
+
problems.push("name is required");
|
|
625
|
+
if (typeof def.version !== "string" || def.version === "")
|
|
626
|
+
problems.push("version is required");
|
|
627
|
+
if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
|
|
628
|
+
problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
|
|
629
|
+
}
|
|
630
|
+
if (def.activate !== undefined && typeof def.activate !== "function") {
|
|
631
|
+
problems.push("activate must be a function");
|
|
632
|
+
}
|
|
633
|
+
if (def.permissions !== undefined) {
|
|
634
|
+
if (!Array.isArray(def.permissions))
|
|
635
|
+
problems.push("permissions must be an array");
|
|
636
|
+
else
|
|
637
|
+
for (const p of def.permissions)
|
|
638
|
+
if (!PERMISSIONS.includes(p))
|
|
639
|
+
problems.push(`unknown permission "${String(p)}"`);
|
|
640
|
+
}
|
|
641
|
+
if (def.settings !== undefined) {
|
|
642
|
+
for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
|
|
643
|
+
problems.push(`plugin ${p}`);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
if (def.commands !== undefined) {
|
|
647
|
+
if (!Array.isArray(def.commands))
|
|
648
|
+
problems.push("commands must be an array");
|
|
649
|
+
else {
|
|
650
|
+
checkLocalIds("command", def.commands, problems);
|
|
651
|
+
for (const c of def.commands) {
|
|
652
|
+
const name = typeof c?.id === "string" ? c.id : "?";
|
|
653
|
+
if (typeof c?.name !== "string")
|
|
654
|
+
problems.push(`command "${name}": name is required`);
|
|
655
|
+
if (typeof c?.run !== "function")
|
|
656
|
+
problems.push(`command "${name}": run is required`);
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
if (def.onboarding !== undefined)
|
|
661
|
+
problems.push(...checkOnboarding(def));
|
|
662
|
+
const sources = def.optionSources ?? {};
|
|
663
|
+
if (typeof sources !== "object")
|
|
664
|
+
problems.push("optionSources must be an object");
|
|
665
|
+
else
|
|
666
|
+
for (const [name, fn] of Object.entries(sources))
|
|
667
|
+
if (typeof fn !== "function")
|
|
668
|
+
problems.push(`option source "${name}" must be a function`);
|
|
669
|
+
if (!Array.isArray(def.actions))
|
|
670
|
+
return [...problems, "actions must be an array"];
|
|
671
|
+
checkLocalIds("action", def.actions, problems);
|
|
672
|
+
for (const action of def.actions) {
|
|
673
|
+
const name = typeof action?.id === "string" ? action.id : "?";
|
|
674
|
+
if (typeof action?.name !== "string")
|
|
675
|
+
problems.push(`action "${name}": name is required`);
|
|
676
|
+
const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
|
|
677
|
+
const hasRun = typeof action?.run === "function";
|
|
678
|
+
if (!hasComponent && !hasRun)
|
|
679
|
+
problems.push(`action "${name}": needs run or component`);
|
|
680
|
+
if (action?.look !== undefined && typeof action.look !== "function") {
|
|
681
|
+
problems.push(`action "${name}": look must be a function`);
|
|
682
|
+
}
|
|
683
|
+
const slots = action?.slots ?? ["key"];
|
|
684
|
+
if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
|
|
685
|
+
problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
|
|
686
|
+
}
|
|
687
|
+
for (const p of checkSchema(action?.settings ?? {}, sources)) {
|
|
688
|
+
problems.push(`action "${name}": ${p}`);
|
|
689
|
+
}
|
|
690
|
+
for (const [key, field] of Object.entries(action?.settings ?? {})) {
|
|
691
|
+
if (field?.type === "secret") {
|
|
692
|
+
problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
if (def.state !== undefined) {
|
|
697
|
+
if (!Array.isArray(def.state))
|
|
698
|
+
problems.push("state must be an array");
|
|
699
|
+
else {
|
|
700
|
+
checkLocalIds("state", def.state, problems);
|
|
701
|
+
for (const s of def.state) {
|
|
702
|
+
const name = typeof s?.id === "string" ? s.id : "?";
|
|
703
|
+
if (typeof s?.name !== "string")
|
|
704
|
+
problems.push(`state "${name}": name is required`);
|
|
705
|
+
if (!["number", "string", "boolean", "json"].includes(s?.type)) {
|
|
706
|
+
problems.push(`state "${name}": type must be number, string, boolean or json`);
|
|
707
|
+
}
|
|
708
|
+
if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
|
|
709
|
+
problems.push(`state "${name}": poll needs read() and everyMs > 0`);
|
|
710
|
+
}
|
|
711
|
+
if (s?.start !== undefined && typeof s.start !== "function") {
|
|
712
|
+
problems.push(`state "${name}": start must be a function`);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
if (def.triggers !== undefined) {
|
|
718
|
+
if (!Array.isArray(def.triggers))
|
|
719
|
+
problems.push("triggers must be an array");
|
|
720
|
+
else {
|
|
721
|
+
checkLocalIds("trigger", def.triggers, problems);
|
|
722
|
+
for (const t of def.triggers) {
|
|
723
|
+
const name = typeof t?.id === "string" ? t.id : "?";
|
|
724
|
+
if (typeof t?.name !== "string")
|
|
725
|
+
problems.push(`trigger "${name}": name is required`);
|
|
726
|
+
if (typeof t?.subscribe !== "function") {
|
|
727
|
+
problems.push(`trigger "${name}": subscribe is required`);
|
|
728
|
+
}
|
|
729
|
+
for (const p of checkSchema(t?.settings ?? {}, sources)) {
|
|
730
|
+
problems.push(`trigger "${name}": ${p}`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
return problems;
|
|
736
|
+
}
|
|
737
|
+
function checkOnboarding(def) {
|
|
738
|
+
const onboarding = def.onboarding;
|
|
739
|
+
if (!Array.isArray(onboarding?.steps))
|
|
740
|
+
return ["onboarding: steps must be an array"];
|
|
741
|
+
const problems = [];
|
|
742
|
+
checkLocalIds("onboarding step", onboarding.steps, problems);
|
|
743
|
+
const settings = def.settings ?? {};
|
|
744
|
+
const commands = new Set((def.commands ?? []).map((c) => c.id));
|
|
745
|
+
for (const step of onboarding.steps) {
|
|
746
|
+
const name = typeof step?.id === "string" ? step.id : "?";
|
|
747
|
+
if (typeof step?.title !== "string")
|
|
748
|
+
problems.push(`onboarding step "${name}": title is required`);
|
|
749
|
+
for (const key of step?.settings ?? []) {
|
|
750
|
+
if (!(key in settings))
|
|
751
|
+
problems.push(`onboarding step "${name}": no setting "${key}"`);
|
|
752
|
+
}
|
|
753
|
+
if (step?.command !== undefined && !commands.has(step.command)) {
|
|
754
|
+
problems.push(`onboarding step "${name}": no command "${step.command}"`);
|
|
755
|
+
}
|
|
756
|
+
if (step?.done !== undefined && typeof step.done !== "function") {
|
|
757
|
+
problems.push(`onboarding step "${name}": done must be a function`);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const page = onboarding.starterPage;
|
|
761
|
+
if (page) {
|
|
762
|
+
const actions = new Set((def.actions ?? []).map((a) => a.id));
|
|
763
|
+
const used = [
|
|
764
|
+
...Object.values(page.keys ?? {}),
|
|
765
|
+
...Object.values(page.sensors ?? {}),
|
|
766
|
+
...page.window ? [page.window] : []
|
|
767
|
+
];
|
|
768
|
+
for (const { action } of used) {
|
|
769
|
+
if (!actions.has(action))
|
|
770
|
+
problems.push(`onboarding starter page: no action "${action}"`);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
return problems;
|
|
774
|
+
}
|
|
775
|
+
// src/client.ts
|
|
776
|
+
function socketUrl(address) {
|
|
777
|
+
const url = new URL(/^[a-z]+:\/\//i.test(address) ? address : `http://${address}`);
|
|
778
|
+
if (!/^(https?|wss?):$/.test(url.protocol))
|
|
779
|
+
throw new Error("use an http or https address");
|
|
780
|
+
url.protocol = /^(https|wss):$/.test(url.protocol) ? "wss:" : "ws:";
|
|
781
|
+
const path = url.pathname.replace(/\/+$/, "").replace(/\/api\/websocket$/, "");
|
|
782
|
+
url.pathname = `${path}/api/websocket`;
|
|
783
|
+
url.search = "";
|
|
784
|
+
url.hash = "";
|
|
785
|
+
return url.toString();
|
|
786
|
+
}
|
|
787
|
+
var toState = (raw) => ({
|
|
788
|
+
state: raw.state,
|
|
789
|
+
name: typeof raw.attributes?.friendly_name === "string" ? raw.attributes.friendly_name : raw.entity_id,
|
|
790
|
+
attributes: raw.attributes ?? {}
|
|
791
|
+
});
|
|
792
|
+
function withEntity(entities, id, state) {
|
|
793
|
+
const dot = id.indexOf(".");
|
|
794
|
+
const domain = id.slice(0, dot);
|
|
795
|
+
const object = id.slice(dot + 1);
|
|
796
|
+
if (dot <= 0 || !object)
|
|
797
|
+
return entities;
|
|
798
|
+
const next = { ...entities[domain] };
|
|
799
|
+
if (state)
|
|
800
|
+
next[object] = state;
|
|
801
|
+
else
|
|
802
|
+
delete next[object];
|
|
803
|
+
return { ...entities, [domain]: next };
|
|
804
|
+
}
|
|
805
|
+
function connectHomeAssistant(address, token, lost, signal, pingMs = 30000) {
|
|
806
|
+
return new Promise((resolve, reject) => {
|
|
807
|
+
let socket;
|
|
808
|
+
try {
|
|
809
|
+
socket = new WebSocket(socketUrl(address));
|
|
810
|
+
} catch {
|
|
811
|
+
reject(new PermanentError(`"${address}" is not a Home Assistant address`));
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
const pending = new Map;
|
|
815
|
+
const listeners = new Set;
|
|
816
|
+
let entities = {};
|
|
817
|
+
let ready = false;
|
|
818
|
+
let next = 1;
|
|
819
|
+
let failure;
|
|
820
|
+
let heartbeat;
|
|
821
|
+
const abort = () => socket.close();
|
|
822
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
823
|
+
const handshake = setTimeout(() => {
|
|
824
|
+
failure = new Error("Home Assistant did not answer");
|
|
825
|
+
socket.close();
|
|
826
|
+
}, 1e4);
|
|
827
|
+
let subscription = 0;
|
|
828
|
+
const command = (message) => new Promise((done, fail) => {
|
|
829
|
+
if (socket.readyState !== WebSocket.OPEN) {
|
|
830
|
+
fail(new Error("Home Assistant is not connected"));
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const id = next++;
|
|
834
|
+
const timer = setTimeout(() => {
|
|
835
|
+
pending.delete(id);
|
|
836
|
+
fail(new Error(`Home Assistant did not answer ${message.type}`));
|
|
837
|
+
}, 1e4);
|
|
838
|
+
pending.set(id, {
|
|
839
|
+
resolve: (r) => {
|
|
840
|
+
clearTimeout(timer);
|
|
841
|
+
done(r);
|
|
842
|
+
},
|
|
843
|
+
reject: (e) => {
|
|
844
|
+
clearTimeout(timer);
|
|
845
|
+
fail(e);
|
|
846
|
+
}
|
|
847
|
+
});
|
|
848
|
+
socket.send(JSON.stringify({ id, ...message }));
|
|
849
|
+
});
|
|
850
|
+
const client = {
|
|
851
|
+
command,
|
|
852
|
+
entities: () => entities,
|
|
853
|
+
onChange: (listener) => {
|
|
854
|
+
listeners.add(listener);
|
|
855
|
+
return () => void listeners.delete(listener);
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
const start = async () => {
|
|
859
|
+
subscription = next;
|
|
860
|
+
const early = [];
|
|
861
|
+
const collect = (change) => {
|
|
862
|
+
const s = change.state;
|
|
863
|
+
if (s)
|
|
864
|
+
early.push({ entity_id: change.entity, state: s.state, attributes: s.attributes });
|
|
865
|
+
};
|
|
866
|
+
listeners.add(collect);
|
|
867
|
+
await command({ type: "subscribe_events", event_type: "state_changed" });
|
|
868
|
+
const states = await command({ type: "get_states" });
|
|
869
|
+
listeners.delete(collect);
|
|
870
|
+
for (const raw of [...states, ...early]) {
|
|
871
|
+
entities = withEntity(entities, raw.entity_id, toState(raw));
|
|
872
|
+
}
|
|
873
|
+
};
|
|
874
|
+
socket.onmessage = (message) => {
|
|
875
|
+
let packet;
|
|
876
|
+
try {
|
|
877
|
+
packet = JSON.parse(String(message.data));
|
|
878
|
+
} catch {
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
switch (packet.type) {
|
|
882
|
+
case "auth_required":
|
|
883
|
+
socket.send(JSON.stringify({ type: "auth", access_token: token }));
|
|
884
|
+
break;
|
|
885
|
+
case "auth_invalid":
|
|
886
|
+
failure = new PermanentError("Home Assistant rejected the access token");
|
|
887
|
+
socket.close();
|
|
888
|
+
break;
|
|
889
|
+
case "auth_ok":
|
|
890
|
+
start().then(() => {
|
|
891
|
+
clearTimeout(handshake);
|
|
892
|
+
ready = true;
|
|
893
|
+
heartbeat = setInterval(() => {
|
|
894
|
+
command({ type: "ping" }).catch(() => socket.close());
|
|
895
|
+
}, pingMs);
|
|
896
|
+
resolve({ value: client, close: () => socket.close() });
|
|
897
|
+
}, (error) => {
|
|
898
|
+
failure = error;
|
|
899
|
+
socket.close();
|
|
900
|
+
});
|
|
901
|
+
break;
|
|
902
|
+
case "pong":
|
|
903
|
+
pending.get(packet.id)?.resolve(undefined);
|
|
904
|
+
pending.delete(packet.id);
|
|
905
|
+
break;
|
|
906
|
+
case "result": {
|
|
907
|
+
const waiter = pending.get(packet.id);
|
|
908
|
+
if (!waiter)
|
|
909
|
+
return;
|
|
910
|
+
pending.delete(packet.id);
|
|
911
|
+
if (packet.success)
|
|
912
|
+
waiter.resolve(packet.result);
|
|
913
|
+
else {
|
|
914
|
+
const error = packet.error;
|
|
915
|
+
waiter.reject(new Error(error?.message ?? "Home Assistant refused the command"));
|
|
916
|
+
}
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
case "event": {
|
|
920
|
+
if (packet.id !== subscription)
|
|
921
|
+
return;
|
|
922
|
+
const data = packet.event?.data;
|
|
923
|
+
const entity = data?.entity_id;
|
|
924
|
+
if (typeof entity !== "string")
|
|
925
|
+
return;
|
|
926
|
+
const raw = data?.new_state;
|
|
927
|
+
const state = raw ? toState(raw) : undefined;
|
|
928
|
+
const from = data?.old_state?.state;
|
|
929
|
+
entities = withEntity(entities, entity, state);
|
|
930
|
+
for (const listener of [...listeners])
|
|
931
|
+
listener({ entity, state, from });
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
};
|
|
936
|
+
socket.onclose = () => {
|
|
937
|
+
clearTimeout(handshake);
|
|
938
|
+
clearInterval(heartbeat);
|
|
939
|
+
signal.removeEventListener("abort", abort);
|
|
940
|
+
const error = failure ?? new Error(ready ? "Home Assistant closed the connection" : `cannot reach ${address}`);
|
|
941
|
+
for (const waiter of [...pending.values()])
|
|
942
|
+
waiter.reject(error);
|
|
943
|
+
pending.clear();
|
|
944
|
+
if (ready)
|
|
945
|
+
lost(error);
|
|
946
|
+
else
|
|
947
|
+
reject(error);
|
|
948
|
+
};
|
|
949
|
+
socket.onerror = () => {};
|
|
950
|
+
});
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// src/index.tsx
|
|
954
|
+
var context;
|
|
955
|
+
var entityListeners = new Set;
|
|
956
|
+
var changeListeners = new Set;
|
|
957
|
+
var current;
|
|
958
|
+
function publish(entities) {
|
|
959
|
+
current = entities;
|
|
960
|
+
for (const listener of [...entityListeners])
|
|
961
|
+
listener(entities);
|
|
962
|
+
}
|
|
963
|
+
var connection = new ManagedConnection({
|
|
964
|
+
open: async (lost, signal) => {
|
|
965
|
+
const settings = context?.settings() ?? {};
|
|
966
|
+
const address = String(settings.url || "");
|
|
967
|
+
const token = String(settings.token || "");
|
|
968
|
+
if (!address || !token) {
|
|
969
|
+
throw new PermanentError("Set the address and an access token in the plugin's settings");
|
|
970
|
+
}
|
|
971
|
+
const link = await connectHomeAssistant(address, token, (error) => {
|
|
972
|
+
publish(undefined);
|
|
973
|
+
lost(error);
|
|
974
|
+
}, signal);
|
|
975
|
+
const off = link.value.onChange((change) => {
|
|
976
|
+
publish(link.value.entities());
|
|
977
|
+
context?.emit("state", change);
|
|
978
|
+
for (const listener of [...changeListeners])
|
|
979
|
+
listener(change);
|
|
980
|
+
});
|
|
981
|
+
publish(link.value.entities());
|
|
982
|
+
return {
|
|
983
|
+
value: link.value,
|
|
984
|
+
close: () => {
|
|
985
|
+
off();
|
|
986
|
+
link.close();
|
|
987
|
+
publish(undefined);
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
},
|
|
991
|
+
onStatus: (state, error) => {
|
|
992
|
+
if (state === "connected")
|
|
993
|
+
context?.status("Connected to Home Assistant", "ok");
|
|
994
|
+
else if (state === "disconnected") {
|
|
995
|
+
context?.status(error?.message, error ? "error" : "info");
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
function splitEntity(entity) {
|
|
1000
|
+
const match = /^([a-z0-9_]+)\.([a-z0-9_]+)$/.exec(entity.trim().toLowerCase());
|
|
1001
|
+
if (!match)
|
|
1002
|
+
throw new Error(`"${entity}" is not an entity id (like light.kitchen)`);
|
|
1003
|
+
return { domain: match[1], object: match[2] };
|
|
1004
|
+
}
|
|
1005
|
+
function entityPath(entity) {
|
|
1006
|
+
const [domain = "", object = ""] = entity.trim().toLowerCase().split(".");
|
|
1007
|
+
return `ha.entities[${JSON.stringify(domain)}][${JSON.stringify(object)}]`;
|
|
1008
|
+
}
|
|
1009
|
+
var entityField = {
|
|
1010
|
+
type: "text",
|
|
1011
|
+
label: "Entity",
|
|
1012
|
+
source: "entities",
|
|
1013
|
+
placeholder: "light.kitchen"
|
|
1014
|
+
};
|
|
1015
|
+
var DOMAIN_ICONS = {
|
|
1016
|
+
light: { icon: "lucide/lightbulb", off: "lucide/lightbulb-off", on: "on" },
|
|
1017
|
+
switch: { icon: "lucide/toggle-right", off: "lucide/toggle-left", on: "on" },
|
|
1018
|
+
input_boolean: { icon: "lucide/toggle-right", off: "lucide/toggle-left", on: "on" },
|
|
1019
|
+
fan: { icon: "lucide/fan", on: "on" },
|
|
1020
|
+
lock: { icon: "lucide/lock", off: "lucide/lock-open", on: "locked" },
|
|
1021
|
+
cover: { icon: "lucide/blinds", on: "open" },
|
|
1022
|
+
media_player: { icon: "lucide/speaker", on: "playing" },
|
|
1023
|
+
climate: { icon: "lucide/thermometer" },
|
|
1024
|
+
sensor: { icon: "lucide/gauge" },
|
|
1025
|
+
binary_sensor: { icon: "lucide/radar", on: "on" },
|
|
1026
|
+
scene: { icon: "lucide/sparkles" },
|
|
1027
|
+
script: { icon: "lucide/scroll-text" },
|
|
1028
|
+
automation: { icon: "lucide/workflow", on: "on" },
|
|
1029
|
+
person: { icon: "lucide/user", on: "home" },
|
|
1030
|
+
vacuum: { icon: "lucide/bot", on: "cleaning" }
|
|
1031
|
+
};
|
|
1032
|
+
var HOME_ICON = { icon: "si/SiHomeassistant", off: undefined, on: undefined };
|
|
1033
|
+
var domainOf = (entity) => entity.trim().toLowerCase().split(".")[0] ?? "";
|
|
1034
|
+
var READINGS = new Set(["sensor", "climate", "person", "media_player"]);
|
|
1035
|
+
var entityLook = (entity, title, background) => {
|
|
1036
|
+
const path = entityPath(entity);
|
|
1037
|
+
const domain = domainOf(entity);
|
|
1038
|
+
const { icon, off, on } = DOMAIN_ICONS[domain] ?? HOME_ICON;
|
|
1039
|
+
const lit = on ? `${path}.state == ${JSON.stringify(on)}` : "true";
|
|
1040
|
+
const reading = READINGS.has(domain);
|
|
1041
|
+
const name = title || `{{${path}.name ?? ${JSON.stringify(entity || "Entity")}}}`;
|
|
1042
|
+
return {
|
|
1043
|
+
background,
|
|
1044
|
+
layers: [
|
|
1045
|
+
iconLayer("on", icon, {
|
|
1046
|
+
color: on ? "#fbbf24" : "#ffffff",
|
|
1047
|
+
size: 48,
|
|
1048
|
+
position: "top",
|
|
1049
|
+
visible: lit
|
|
1050
|
+
}),
|
|
1051
|
+
iconLayer("off", off ?? icon, {
|
|
1052
|
+
color: "#6b7280",
|
|
1053
|
+
size: 48,
|
|
1054
|
+
position: "top",
|
|
1055
|
+
visible: `!(${lit})`
|
|
1056
|
+
}),
|
|
1057
|
+
textLayer("label", reading ? `{{${path}.state ?? "N/A"}}{{${path}.attributes.unit_of_measurement ?? ""}}` : name, { size: reading ? 17 : 12, position: "bottom" })
|
|
1058
|
+
]
|
|
1059
|
+
};
|
|
1060
|
+
};
|
|
1061
|
+
var OPERATIONS = [
|
|
1062
|
+
{ value: "toggle", label: "Toggle" },
|
|
1063
|
+
{ value: "turn_on", label: "Turn on" },
|
|
1064
|
+
{ value: "turn_off", label: "Turn off" }
|
|
1065
|
+
];
|
|
1066
|
+
var entity = defineAction({
|
|
1067
|
+
id: "entity",
|
|
1068
|
+
name: "Entity",
|
|
1069
|
+
description: "Shows an entity's state; pressing it toggles it or turns it on or off.",
|
|
1070
|
+
category: "Home Assistant",
|
|
1071
|
+
icon: "house",
|
|
1072
|
+
slots: ["key", "sensor", "window"],
|
|
1073
|
+
settings: {
|
|
1074
|
+
entity: entityField,
|
|
1075
|
+
operation: { type: "select", label: "When pressed", default: "toggle", options: OPERATIONS },
|
|
1076
|
+
text: { type: "text", label: "Title", placeholder: "Defaults to the entity's name" },
|
|
1077
|
+
background: { type: "color", label: "Background", default: "#111827" }
|
|
1078
|
+
},
|
|
1079
|
+
run: async ({ settings }) => {
|
|
1080
|
+
const { domain, object } = splitEntity(settings.entity);
|
|
1081
|
+
const entity_id = `${domain}.${object}`;
|
|
1082
|
+
const call = (ha, service) => ha.command({
|
|
1083
|
+
type: "call_service",
|
|
1084
|
+
domain: "homeassistant",
|
|
1085
|
+
service,
|
|
1086
|
+
target: { entity_id }
|
|
1087
|
+
});
|
|
1088
|
+
return connection.with(async (ha) => {
|
|
1089
|
+
const before = ha.entities()[domain]?.[object]?.state;
|
|
1090
|
+
if (before === undefined)
|
|
1091
|
+
throw new Error(`no entity ${entity_id}`);
|
|
1092
|
+
await call(ha, settings.operation);
|
|
1093
|
+
const restore = before === "on" ? "turn_on" : before === "off" ? "turn_off" : undefined;
|
|
1094
|
+
return {
|
|
1095
|
+
label: `${settings.operation} ${entity_id}`,
|
|
1096
|
+
...restore && {
|
|
1097
|
+
undo: () => connection.with((again) => call(again, restore))
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
});
|
|
1101
|
+
},
|
|
1102
|
+
look: (s) => entityLook(s.entity, s.text, s.background)
|
|
1103
|
+
});
|
|
1104
|
+
function serviceData(text) {
|
|
1105
|
+
if (!text.trim())
|
|
1106
|
+
return {};
|
|
1107
|
+
let value;
|
|
1108
|
+
try {
|
|
1109
|
+
value = JSON.parse(text);
|
|
1110
|
+
} catch {
|
|
1111
|
+
throw new Error("the data is not valid JSON");
|
|
1112
|
+
}
|
|
1113
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1114
|
+
throw new Error("the data must be a JSON object");
|
|
1115
|
+
}
|
|
1116
|
+
return value;
|
|
1117
|
+
}
|
|
1118
|
+
var service = defineAction({
|
|
1119
|
+
id: "service",
|
|
1120
|
+
name: "Call a service",
|
|
1121
|
+
description: "Calls any Home Assistant service, e.g. scene.turn_on or light.turn_on.",
|
|
1122
|
+
category: "Home Assistant",
|
|
1123
|
+
icon: "wand-sparkles",
|
|
1124
|
+
slots: ["key", "sensor"],
|
|
1125
|
+
settings: {
|
|
1126
|
+
service: {
|
|
1127
|
+
type: "text",
|
|
1128
|
+
label: "Service",
|
|
1129
|
+
source: "services",
|
|
1130
|
+
placeholder: "light.turn_on"
|
|
1131
|
+
},
|
|
1132
|
+
entity: { ...entityField, description: "Leave empty for services without a target." },
|
|
1133
|
+
data: {
|
|
1134
|
+
type: "text",
|
|
1135
|
+
label: "Data (JSON)",
|
|
1136
|
+
multiline: true,
|
|
1137
|
+
placeholder: '{ "brightness_pct": 40 }'
|
|
1138
|
+
},
|
|
1139
|
+
text: { type: "text", label: "Text", placeholder: "Defaults to the service" },
|
|
1140
|
+
background: { type: "color", label: "Background", default: "#0c4a6e" }
|
|
1141
|
+
},
|
|
1142
|
+
run: async ({ settings }) => {
|
|
1143
|
+
const { domain, object } = splitEntity(settings.service);
|
|
1144
|
+
const data = serviceData(settings.data);
|
|
1145
|
+
await connection.with((ha) => ha.command({
|
|
1146
|
+
type: "call_service",
|
|
1147
|
+
domain,
|
|
1148
|
+
service: object,
|
|
1149
|
+
service_data: data,
|
|
1150
|
+
...settings.entity && { target: { entity_id: settings.entity.trim() } }
|
|
1151
|
+
}));
|
|
1152
|
+
return { label: `${settings.service} ${settings.entity}`.trim() };
|
|
1153
|
+
},
|
|
1154
|
+
look: (s) => iconLook({
|
|
1155
|
+
icon: DOMAIN_ICONS[domainOf(s.service)]?.icon ?? "lucide/wand-sparkles",
|
|
1156
|
+
background: s.background,
|
|
1157
|
+
caption: s.text || s.service.split(".")[1]?.replace(/_/g, " ") || ""
|
|
1158
|
+
})
|
|
1159
|
+
});
|
|
1160
|
+
var stateChanged = defineTrigger({
|
|
1161
|
+
id: "state-changed",
|
|
1162
|
+
name: "When a Home Assistant entity changes",
|
|
1163
|
+
settings: {
|
|
1164
|
+
entity: entityField,
|
|
1165
|
+
to: { type: "text", label: "To the state", placeholder: "Any state" }
|
|
1166
|
+
},
|
|
1167
|
+
subscribe: ({ settings, fire }) => {
|
|
1168
|
+
const { domain, object } = splitEntity(settings.entity);
|
|
1169
|
+
const wanted = `${domain}.${object}`;
|
|
1170
|
+
const listener = (change) => {
|
|
1171
|
+
if (change.entity !== wanted)
|
|
1172
|
+
return;
|
|
1173
|
+
const state = change.state?.state;
|
|
1174
|
+
if (state === change.from)
|
|
1175
|
+
return;
|
|
1176
|
+
if (!settings.to || state === settings.to.trim()) {
|
|
1177
|
+
fire({ entity: wanted, state, from: change.from });
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
changeListeners.add(listener);
|
|
1181
|
+
const release = connection.hold();
|
|
1182
|
+
return () => {
|
|
1183
|
+
changeListeners.delete(listener);
|
|
1184
|
+
release();
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
});
|
|
1188
|
+
var src_default = definePlugin({
|
|
1189
|
+
id: "@sdeck/plugin-home-assistant",
|
|
1190
|
+
name: "Home Assistant",
|
|
1191
|
+
version: "0.1.0",
|
|
1192
|
+
namespace: "ha",
|
|
1193
|
+
description: "Entity states and service calls over Home Assistant's WebSocket API.",
|
|
1194
|
+
author: "sdeck",
|
|
1195
|
+
permissions: ["network"],
|
|
1196
|
+
settings: {
|
|
1197
|
+
url: { type: "text", label: "Address", placeholder: "http://homeassistant.local:8123" },
|
|
1198
|
+
token: {
|
|
1199
|
+
type: "secret",
|
|
1200
|
+
label: "Access token",
|
|
1201
|
+
description: "A long-lived access token from your Home Assistant profile."
|
|
1202
|
+
}
|
|
1203
|
+
},
|
|
1204
|
+
onboarding: {
|
|
1205
|
+
steps: [
|
|
1206
|
+
{
|
|
1207
|
+
id: "token",
|
|
1208
|
+
title: "Connect to Home Assistant",
|
|
1209
|
+
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**.",
|
|
1210
|
+
link: {
|
|
1211
|
+
label: "About access tokens",
|
|
1212
|
+
url: "https://www.home-assistant.io/docs/authentication/#your-account-profile"
|
|
1213
|
+
},
|
|
1214
|
+
settings: ["url", "token"]
|
|
1215
|
+
},
|
|
1216
|
+
{
|
|
1217
|
+
id: "connect",
|
|
1218
|
+
title: "Test the connection",
|
|
1219
|
+
command: "connect"
|
|
1220
|
+
}
|
|
1221
|
+
],
|
|
1222
|
+
starterPage: false
|
|
1223
|
+
},
|
|
1224
|
+
commands: [
|
|
1225
|
+
{
|
|
1226
|
+
id: "connect",
|
|
1227
|
+
name: "Test the connection",
|
|
1228
|
+
run: async () => {
|
|
1229
|
+
connection.restart();
|
|
1230
|
+
await connection.with(() => {});
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
],
|
|
1234
|
+
actions: [entity, service],
|
|
1235
|
+
triggers: [stateChanged],
|
|
1236
|
+
optionSources: {
|
|
1237
|
+
entities: () => connection.with((ha) => Object.entries(ha.entities()).flatMap(([domain, objects]) => Object.entries(objects).map(([object, e]) => ({
|
|
1238
|
+
value: `${domain}.${object}`,
|
|
1239
|
+
label: e.name
|
|
1240
|
+
}))).sort((a, b) => a.value.localeCompare(b.value))),
|
|
1241
|
+
services: () => connection.with(async (ha) => {
|
|
1242
|
+
const services = await ha.command({ type: "get_services" });
|
|
1243
|
+
return Object.entries(services).flatMap(([domain, names]) => Object.keys(names).map((name) => `${domain}.${name}`)).sort().map((value) => ({ value, label: value }));
|
|
1244
|
+
})
|
|
1245
|
+
},
|
|
1246
|
+
state: [
|
|
1247
|
+
{
|
|
1248
|
+
id: "entities",
|
|
1249
|
+
name: "Entities",
|
|
1250
|
+
type: "json",
|
|
1251
|
+
description: "ha.entities.light.kitchen.state, .name, .attributes",
|
|
1252
|
+
start: (set) => {
|
|
1253
|
+
const listener = (entities) => set(entities);
|
|
1254
|
+
entityListeners.add(listener);
|
|
1255
|
+
listener(current);
|
|
1256
|
+
const release = connection.hold();
|
|
1257
|
+
return () => {
|
|
1258
|
+
entityListeners.delete(listener);
|
|
1259
|
+
release();
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
},
|
|
1263
|
+
{
|
|
1264
|
+
id: "connected",
|
|
1265
|
+
name: "Connected",
|
|
1266
|
+
type: "boolean",
|
|
1267
|
+
start: (set) => {
|
|
1268
|
+
const listener = (entities) => set(entities !== undefined);
|
|
1269
|
+
entityListeners.add(listener);
|
|
1270
|
+
listener(current);
|
|
1271
|
+
const release = connection.hold();
|
|
1272
|
+
return () => {
|
|
1273
|
+
entityListeners.delete(listener);
|
|
1274
|
+
release();
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
],
|
|
1279
|
+
activate(activated) {
|
|
1280
|
+
context = activated;
|
|
1281
|
+
let settings = JSON.stringify(activated.settings());
|
|
1282
|
+
const off = activated.onSettings(() => {
|
|
1283
|
+
const next = JSON.stringify(activated.settings());
|
|
1284
|
+
if (next === settings)
|
|
1285
|
+
return;
|
|
1286
|
+
settings = next;
|
|
1287
|
+
connection.restart();
|
|
1288
|
+
});
|
|
1289
|
+
return () => {
|
|
1290
|
+
off();
|
|
1291
|
+
connection.close();
|
|
1292
|
+
publish(undefined);
|
|
1293
|
+
context = undefined;
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
});
|
|
1297
|
+
export {
|
|
1298
|
+
connectHomeAssistant,
|
|
1299
|
+
src_default as default,
|
|
1300
|
+
domainOf,
|
|
1301
|
+
entityPath,
|
|
1302
|
+
serviceData,
|
|
1303
|
+
socketUrl,
|
|
1304
|
+
splitEntity,
|
|
1305
|
+
withEntity
|
|
1306
|
+
};
|
|
1307
|
+
|
|
1308
|
+
//# debugId=CA32DD17EDF0FB6B64756E2164756E21
|