@camstack/server 1.2.840 → 1.2.842

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.
Files changed (111) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/api/oauth2/oauth2-routes.js +50 -6
  3. package/dist/api/trpc/generated-cap-routers.js +16 -0
  4. package/dist/core/addon/addon-registry.service.js +4 -0
  5. package/dist/core/addon/addon-route-request.js +18 -0
  6. package/dist/main.js +8 -5
  7. package/package.json +16 -8
  8. package/system/dist/addon-routes/addon-route-registry.d.ts +27 -1
  9. package/system/dist/addon-runner.js +7 -3
  10. package/system/dist/addon-runner.mjs +7 -3
  11. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  12. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +1 -1
  13. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  14. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +1 -1
  15. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  16. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  17. package/system/dist/builtins/autotrack/index.js +1 -1
  18. package/system/dist/builtins/autotrack/index.mjs +1 -1
  19. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  20. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +2 -2
  21. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  22. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  23. package/system/dist/builtins/camera-grid/index.js +1 -1
  24. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  25. package/system/dist/builtins/composer/composer.addon.js +5 -5
  26. package/system/dist/builtins/composer/composer.addon.mjs +5 -5
  27. package/system/dist/builtins/console-logging/index.js +1 -1
  28. package/system/dist/builtins/console-logging/index.mjs +1 -1
  29. package/system/dist/builtins/core-blocks/composition-api.d.ts +2 -2
  30. package/system/dist/builtins/core-blocks/composition-sources.d.ts +9 -2
  31. package/system/dist/builtins/core-blocks/core-blocks.addon.d.ts +2 -0
  32. package/system/dist/builtins/core-blocks/core-blocks.addon.js +598 -395
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +598 -395
  34. package/system/dist/builtins/core-blocks/fan-link-forward.d.ts +42 -0
  35. package/system/dist/builtins/core-blocks/fan-presets-service.d.ts +25 -39
  36. package/system/dist/builtins/core-blocks/fan-presets-wiring.d.ts +5 -3
  37. package/system/dist/builtins/core-blocks/migrations/helper-to-customize.d.ts +3 -1
  38. package/system/dist/builtins/core-blocks/power-source-service.d.ts +2 -0
  39. package/system/dist/builtins/core-blocks/timed-run/timed-run-service.d.ts +8 -2
  40. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  41. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  42. package/system/dist/builtins/device-manager/device-bindings-store.d.ts +8 -5
  43. package/system/dist/builtins/device-manager/device-manager.addon.js +116 -22
  44. package/system/dist/builtins/device-manager/device-manager.addon.mjs +116 -22
  45. package/system/dist/builtins/device-manager/device-row-store.d.ts +0 -52
  46. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  47. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  48. package/system/dist/builtins/keychain/index.js +4 -4
  49. package/system/dist/builtins/keychain/index.mjs +4 -4
  50. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  51. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  52. package/system/dist/builtins/local-auth/local-auth.addon.js +21 -7
  53. package/system/dist/builtins/local-auth/local-auth.addon.mjs +21 -7
  54. package/system/dist/builtins/local-auth/oauth-grants.d.ts +9 -1
  55. package/system/dist/builtins/local-auth/oauth-session-manager.d.ts +8 -0
  56. package/system/dist/builtins/local-auth/record-kinds.d.ts +2 -0
  57. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  58. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  59. package/system/dist/builtins/loki-logging/index.js +1 -1
  60. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  61. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  62. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +1 -1
  63. package/system/dist/builtins/platform-probe/index.js +1 -1
  64. package/system/dist/builtins/platform-probe/index.mjs +1 -1
  65. package/system/dist/builtins/record-entries/index.js +1 -1
  66. package/system/dist/builtins/record-entries/index.mjs +1 -1
  67. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  68. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  69. package/system/dist/builtins/snapshot/index.js +1 -1
  70. package/system/dist/builtins/snapshot/index.mjs +1 -1
  71. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  72. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
  73. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  74. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  75. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +3 -3
  76. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +3 -3
  77. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  78. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  79. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  80. package/system/dist/builtins/system-config/system-config.addon.mjs +3 -3
  81. package/system/dist/builtins/winston-logging/index.js +1 -1
  82. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  83. package/system/dist/{capture-engine-7E2O4-UN.js → capture-engine-DSrJUGYs.js} +1 -1
  84. package/system/dist/{capture-engine-B5IBWIRT.mjs → capture-engine-DySELkE_.mjs} +1 -1
  85. package/system/dist/{composition-sources-DLtc8lSL.js → composition-sources-CNfFz3Cz.js} +32 -5
  86. package/system/dist/{composition-sources-Cfqn4cly.mjs → composition-sources-DZ4E9FFU.mjs} +32 -5
  87. package/system/dist/{constants-DjsgCnZk.mjs → constants-BEXN_b1Y.mjs} +1 -1
  88. package/system/dist/{constants-Cc70YreG.js → constants-DkgFDCQ7.js} +1 -1
  89. package/system/dist/{device-ca-CVP5h3u1.mjs → device-ca-Dk_9f4MY.mjs} +1 -1
  90. package/system/dist/{device-ca-C6JqeFfK.js → device-ca-sYcSz-Fv.js} +1 -1
  91. package/system/dist/{dist-OmrC_RZs.mjs → dist-4jAoRtpT.mjs} +1700 -363
  92. package/system/dist/{dist-CLnTYKFn.js → dist-LQWK1_M4.js} +1753 -374
  93. package/system/dist/file-host-worker.js +1 -1
  94. package/system/dist/file-host-worker.mjs +1 -1
  95. package/system/dist/{hub-identity-CKQVXf4o.mjs → hub-identity-BxGHDga-.mjs} +1 -1
  96. package/system/dist/{hub-identity-TrZcnJkB.js → hub-identity-haC7V8-b.js} +1 -1
  97. package/system/dist/{hub-mdns-ciao-C8G0K1Z1.mjs → hub-mdns-ciao-Birwi8W5.mjs} +2 -2
  98. package/system/dist/{hub-mdns-ciao-ocg6suyX.js → hub-mdns-ciao-zxNvdRQz.js} +2 -2
  99. package/system/dist/index.d.ts +1 -1
  100. package/system/dist/index.js +63 -13
  101. package/system/dist/index.mjs +62 -14
  102. package/system/dist/kernel/moleculer/child-addon-call-dispatch.d.ts +1 -0
  103. package/system/dist/{legacy-integration-rows-door-BPkJUGaX.mjs → legacy-integration-rows-door-C-hOd-lt.mjs} +1 -1
  104. package/system/dist/{legacy-integration-rows-door-b6CUxtXX.js → legacy-integration-rows-door-CCtcCRjZ.js} +1 -1
  105. package/system/dist/{rename-composition-block-N7lslQJK.js → rename-composition-block-BCZeI3eY.js} +1 -1
  106. package/system/dist/{rename-composition-block-DPlsP1xF.mjs → rename-composition-block-YpAVqp4W.mjs} +1 -1
  107. package/system/dist/{restore-archive-Btc3H-Fg.mjs → restore-archive-BpC3y50e.mjs} +1 -1
  108. package/system/dist/{restore-archive-CcuEoEtj.js → restore-archive-D0Nyukhb.js} +1 -1
  109. package/system/dist/{wal-maintenance-g7yvxLMj.mjs → wal-maintenance-C7jLVFCw.mjs} +0 -0
  110. package/system/dist/{wal-maintenance-B2_uCEi5.js → wal-maintenance-CRiSNk0X.js} +0 -0
  111. package/system/package.json +1 -1
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A write to a fan-control field the operator linked in Customize goes to the
3
+ * linked device (D1034): `setOscillationAxis` and `setPreset` on a fan whose
4
+ * stored composition claims the field are answered by the link — a switch's
5
+ * `setState`, a control's `setValue` — at DISPATCH, through the device-call
6
+ * redirect (D963), so every caller gets the same answer.
7
+ *
8
+ * The links are read from the STORED composition on each call, never kept as
9
+ * a second copy (D676). A field nobody linked is the native provider's: when
10
+ * no requested field is linked the call is not redirected. Writes run in the
11
+ * order of the call and stop at the first refusal, which names the field and
12
+ * lists what already landed. An angle is checked against the linked control's
13
+ * own range, a preset against the linked select's live `options`.
14
+ */
15
+ import { type CompositionSourceRef, type ControlSetValueInput, type CoreBlock, type DeviceCallRedirect, type FanOscillationAxisRefusal, type IScopedLogger } from "@camstack/types";
16
+ /** The live facts of a linked control a write is checked against. */
17
+ export interface LinkedControlReading {
18
+ readonly kind: string;
19
+ readonly options: readonly string[];
20
+ readonly min?: number;
21
+ readonly max?: number;
22
+ }
23
+ export interface FanLinkForwardPorts {
24
+ /** The stored core blocks (Customize compositions among them). */
25
+ readonly blocks: () => readonly Pick<CoreBlock, "source">[];
26
+ /** The device id of a ref; null = it does not exist. Throws when the index did not answer. */
27
+ readonly find: (ref: CompositionSourceRef) => Promise<{
28
+ id: number;
29
+ name: string;
30
+ } | null>;
31
+ /** The linked control's live slice; null when it holds none. Throws when it cannot be read. */
32
+ readonly readControl: (deviceId: number) => Promise<LinkedControlReading | null>;
33
+ readonly setSwitch: (deviceId: number, on: boolean) => Promise<void>;
34
+ readonly setControl: (deviceId: number, control: ControlSetValueInput) => Promise<void>;
35
+ readonly logger: IScopedLogger;
36
+ }
37
+ /** A preset write the linked select refused; the message names the select and the reason. */
38
+ export declare class FanPresetRefusedError extends Error {
39
+ readonly reason: FanOscillationAxisRefusal;
40
+ constructor(reason: FanOscillationAxisRefusal, detail: string);
41
+ }
42
+ export declare function fanLinkForwardRedirect(ports: FanLinkForwardPorts): DeviceCallRedirect;
@@ -1,24 +1,22 @@
1
1
  /**
2
- * The `fan-presets` cap: named settings an operator composes for a fan — its
3
- * own fields (speed, oscillation, direction, native preset) and the devices
4
- * that sit in the same container (a light, a control). A preset is a short
5
- * sequence of action steps kept in the fan's settings store (D865, key
2
+ * The `fan-presets` cap: named DESIRED fan-control states an operator keeps
3
+ * for a fan (D1034) — speed, the fan's preset mode, direction and the
4
+ * oscillation axes — stored in the fan's settings store (D865, key
6
5
  * `fanPresets`).
7
6
  *
8
7
  * Decisions that shape this file:
9
- * - **A step may only touch the fan or one of its siblings.** The sibling
10
- * set is the children of the fan's parent device (the container), or the
11
- * fan's own children when it has none. Checked at save AND again at apply,
12
- * because the container changes after a preset was written.
13
- * - **Apply runs the shared step runner** (`buildActionSteps` + `runSteps`),
14
- * in order, stopping at the first failure; every step is reported and a
15
- * failure names its step (D391). Nothing the operator did not write runs.
16
- * - **Capture never stores a guess.** A reading that is unknown is left out
17
- * and named, never written as 0 (D393).
8
+ * - **A preset touches only the fan, through its own `fan-control` methods.**
9
+ * An axis the operator linked in Customize reaches its sibling device
10
+ * through the link's forward (`fan-link-forward.ts`), so a preset stores no
11
+ * sibling and is never re-judged when the container changes.
12
+ * - **Apply runs in a fixed order and stops at the first failure**: preset,
13
+ * speed, direction, then each axis. Every field is reported — applied,
14
+ * failed, not-run or refused — and a failure names its field (D391).
15
+ * - **Capture never stores a guess.** It reads the fan's merged fan-control
16
+ * state (a linked field reads its link); a reading that is unknown is left
17
+ * out and named, never written as 0 (D393).
18
18
  */
19
- import { type CapCall, type ControlStatus, type FanControlStatus, type FanPreset, type IFanPresetsProvider, type IScopedLogger, type SwitchStatus, DeviceType } from "@camstack/types";
20
- import { type DeviceTemplateDoor } from "./device-template-door.js";
21
- import { type StepConditionDoor } from "./step-condition-door.js";
19
+ import { DeviceType, type FanControlStatus, type FanOscillationAxisResult, type FanPreset, type FanPresetState, type IFanPresetsProvider, type IScopedLogger, type SetOscillationAxisInput } from "@camstack/types";
22
20
  /** The per-device store the presets live in. */
23
21
  export interface FanPresetsStore {
24
22
  read(deviceId: number): Promise<readonly FanPreset[]>;
@@ -29,34 +27,34 @@ export interface FanPresetsStore {
29
27
  export interface FanPresetDeviceFacts {
30
28
  readonly name: string;
31
29
  readonly type: DeviceType;
32
- readonly parentDeviceId: number | null;
33
30
  }
34
31
  export interface FanPresetsDevices {
35
32
  describe(deviceId: number): Promise<FanPresetDeviceFacts | null>;
36
- childrenOf(parentDeviceId: number): Promise<readonly number[]>;
37
33
  }
38
- /** Current values, each null when no source answers (D393). */
34
+ /** The fan's merged fan-control state; null when no source answers (D393). */
39
35
  export interface FanPresetsReadings {
40
36
  fan(deviceId: number): Promise<FanControlStatus | null>;
41
- control(deviceId: number): Promise<ControlStatus | null>;
42
- switchState(deviceId: number): Promise<SwitchStatus | null>;
37
+ }
38
+ /** The fan's own fan-control methods; each throws when the call fails. */
39
+ export interface FanPresetsFanControl {
40
+ setPreset(deviceId: number, preset: string): Promise<void>;
41
+ setPercentage(deviceId: number, speed: number): Promise<void>;
42
+ setDirection(deviceId: number, direction: NonNullable<FanPresetState["direction"]>): Promise<void>;
43
+ setOscillationAxis(input: SetOscillationAxisInput): Promise<FanOscillationAxisResult>;
43
44
  }
44
45
  export interface FanPresetsServiceDeps {
45
46
  readonly store: FanPresetsStore;
46
47
  readonly devices: FanPresetsDevices;
47
48
  readonly readings: FanPresetsReadings;
48
- /** Runs one device cap call; throws when it fails. */
49
- invoke(call: CapCall): Promise<void>;
49
+ readonly fanControl: FanPresetsFanControl;
50
50
  readonly logger: IScopedLogger;
51
- readonly now?: () => number;
52
- /** The device template renderer (D1021); a templated step fails where there is none. */
53
- readonly templates?: DeviceTemplateDoor;
54
- readonly conditions?: StepConditionDoor;
55
51
  }
56
52
  type SetResult = Awaited<ReturnType<IFanPresetsProvider["setPresets"]>>;
57
53
  type ApplyResult = Awaited<ReturnType<IFanPresetsProvider["applyPreset"]>>;
58
54
  type CaptureResult = Awaited<ReturnType<IFanPresetsProvider["capturePreset"]>>;
59
55
  type CaptureInput = Parameters<IFanPresetsProvider["capturePreset"]>[0];
56
+ /** Every state path a preset sets, in apply order. */
57
+ export declare function presetFields(state: FanPresetState): readonly string[];
60
58
  export declare class FanPresetsService implements IFanPresetsProvider {
61
59
  private readonly deps;
62
60
  constructor(deps: FanPresetsServiceDeps);
@@ -72,17 +70,5 @@ export declare class FanPresetsService implements IFanPresetsProvider {
72
70
  presetId: string;
73
71
  }): Promise<ApplyResult>;
74
72
  capturePreset(input: CaptureInput): Promise<CaptureResult>;
75
- private captureFanFields;
76
- /** The steps the caller composed, each refreshed with its current value. */
77
- private captureGiven;
78
- /** Every switch and control in the fan's container, read as they are now. */
79
- private captureSiblings;
80
- private fanFieldStep;
81
- private siblingStep;
82
- /** The fan and every device in its container. */
83
- private siblingsOf;
84
- private judgeStep;
85
- /** Every step reported, the offending ones `refused`, nothing run; null when all pass. */
86
- private refusedSteps;
87
73
  }
88
74
  export {};
@@ -1,15 +1,15 @@
1
1
  /**
2
2
  * Builds the `fan-presets` runtime out of what core-blocks owns: the
3
3
  * per-device settings store (D865: a fan's presets live under the key
4
- * `fanPresets`) and the cluster API (a device's type and container, the
5
- * current readings, the cap call a step makes).
4
+ * `fanPresets`) and the cluster API (a device's type, the fan's current
5
+ * fan-control state, the fan-control calls a preset makes).
6
6
  *
7
7
  * Kept out of `core-blocks.addon.ts` so the seams are read and specced
8
8
  * without booting the addon.
9
9
  */
10
10
  import { type AddonApi, type AddonContext, type IScopedLogger } from "@camstack/types";
11
11
  import { FanPresetActionSource } from "./fan-presets-action-source.js";
12
- import { FanPresetsService, type FanPresetsDevices, type FanPresetsReadings, type FanPresetsStore } from "./fan-presets-service.js";
12
+ import { FanPresetsService, type FanPresetsDevices, type FanPresetsFanControl, type FanPresetsReadings, type FanPresetsStore } from "./fan-presets-service.js";
13
13
  /** The key of the device's settings store that holds a fan's presets. */
14
14
  export declare const FAN_PRESETS_STORE_KEY = "fanPresets";
15
15
  type DeviceSettings = Pick<NonNullable<AddonContext["settings"]>, "readDeviceStore" | "writeDeviceStore" | "readDeviceStoreBatch" | "listDeviceStoreIds">;
@@ -25,6 +25,8 @@ export interface FanPresetsRuntime {
25
25
  }
26
26
  export declare function fanPresetsStoreOver(settings: DeviceSettings, logger: IScopedLogger): FanPresetsStore;
27
27
  export declare function fanPresetsDevicesOver(api: () => AddonApi | undefined): FanPresetsDevices;
28
+ /** The fan's own fan-control methods, through `ctx.api` (a linked field is forwarded at dispatch). */
29
+ export declare function fanPresetsFanControlOver(api: () => AddonApi | undefined): FanPresetsFanControl;
28
30
  /** A reading that errors or does not parse is unknown (null), never a default (D393). */
29
31
  export declare function fanPresetsReadingsOver(api: () => AddonApi | undefined, logger: IScopedLogger): FanPresetsReadings;
30
32
  export declare function buildFanPresetsRuntime(deps: FanPresetsRuntimeDeps): FanPresetsRuntime;
@@ -18,7 +18,9 @@
18
18
  * `setState` to it, is kept exactly as it is;
19
19
  * - a heater with no meter runs while its plug is on (the plug as a `switch`
20
20
  * source, identity): it never used the threshold, so none is stored;
21
- * - the `helper` key leaves the composition.
21
+ * - the `helper` key leaves the composition;
22
+ * - a heater's retired `heater` target type becomes a `switch` with the
23
+ * `switch-heater` role (D1033), the same device under the role model.
22
24
  *
23
25
  * The block id, and with it the composed device stableId and the deviceId
24
26
  * the device registry holds, never moves, so the history stays attached. Only
@@ -66,5 +66,7 @@ export declare class PowerSourceService implements IPowerSourceProvider {
66
66
  private lookup;
67
67
  /** The stored link of the device `deviceId`, read from the customizations now. */
68
68
  private linkOf;
69
+ /** The stored link, and whether it names one of the device's own actuators (#462). */
70
+ private storedLinkOf;
69
71
  private refuse;
70
72
  }
@@ -17,7 +17,7 @@
17
17
  * pending deadline silently: the operator already did what the timer would do.
18
18
  * An explicit `cancel` (Stop) is the opposite: it switches the device off too.
19
19
  */
20
- import { DeviceType, type IScopedLogger, type ITimedRunProvider, type TimedRunActuator, type TimedRunStatus } from "@camstack/types";
20
+ import { type IScopedLogger, type ITimedRunProvider, type TimedRunActuator, type TimedRunStatus } from "@camstack/types";
21
21
  import type { PowerSourceScheduler } from "../power-source-service.js";
22
22
  import type { TimedRunRowBody } from "../record-kinds.js";
23
23
  /** The stored deadlines, one per device. */
@@ -39,9 +39,15 @@ export interface TimedRunQuickRuns {
39
39
  readonly read: (deviceId: number) => Promise<number | null>;
40
40
  readonly write: (deviceId: number, duration: number | null) => Promise<void>;
41
41
  }
42
+ /** Which thing a device is: its controls (type) and, among same-control devices, its role. */
43
+ export interface DeviceKind {
44
+ readonly type: string;
45
+ readonly role: string | null;
46
+ }
42
47
  export interface TimedRunServiceDeps {
43
48
  readonly rows: TimedRunRows;
44
- readonly deviceTypeOf: (deviceId: number) => Promise<DeviceType | null>;
49
+ /** The device's type and role, or null when it is gone: together they decide the limit (D1033). */
50
+ readonly deviceKindOf: (deviceId: number) => Promise<DeviceKind | null>;
45
51
  /** Every device whose type offers a timed run: boot publishes each one's status. */
46
52
  readonly timedRunDeviceIds: () => Promise<readonly number[]>;
47
53
  readonly actuation: TimedRunActuation;
@@ -3,8 +3,8 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CLnTYKFn.js");
7
- const require_capture_engine = require("../../capture-engine-7E2O4-UN.js");
6
+ const require_dist = require("../../dist-LQWK1_M4.js");
7
+ const require_capture_engine = require("../../capture-engine-DSrJUGYs.js");
8
8
  const require_retention = require("../../retention-BcOSL6b9.js");
9
9
  let node_crypto = require("node:crypto");
10
10
  //#region src/builtins/device-history/capture/point-writer.ts
@@ -1,5 +1,5 @@
1
- import { Cr as deviceRemovalHookCapability, Dr as deviceTransitionsCapability, En as armRemovalReconcile, Es as InvalidRecordError, H as DEVICE_HISTORY_ENERGY_KEY, Hs as RecordTooLargeError, Mc as isReadingQuantity, Ss as DeviceTransitionSchema, _t as HISTORY_ITEM_CATALOG, fl as DeviceType, gc as defineRecordKinds, gt as HISTORY_CATALOG, hl as EventCategory, hs as BaseAddon, ms as wattMillisecondsToKwh, tt as DeviceRunSchema, vc as emitReadiness, wc as historyUnitFor, wr as deviceRunsCapability, xr as deviceHistoryCapability } from "../../dist-OmrC_RZs.mjs";
2
- import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-B5IBWIRT.mjs";
1
+ import { Cc as defineRecordKinds, Dn as armRemovalReconcile, Dr as deviceRemovalHookCapability, Ns as InvalidRecordError, Or as deviceRunsCapability, Sl as EventCategory, Ss as BaseAddon, Tc as emitReadiness, Tr as deviceHistoryCapability, V as DEVICE_HISTORY_ENERGY_KEY, Ys as RecordTooLargeError, _t as HISTORY_CATALOG, et as DeviceRunSchema, jc as historyUnitFor, jr as deviceTransitionsCapability, ks as DeviceTransitionSchema, vt as HISTORY_ITEM_CATALOG, xs as wattMillisecondsToKwh, yl as DeviceType, zc as isReadingQuantity } from "../../dist-4jAoRtpT.mjs";
2
+ import { a as catalogMetrics, c as DeviceDirectory, d as identityOf, f as subjectIdOf, i as capSeriesKey, l as isRealDeviceType, n as CaptureEngine, o as readPath, r as capItemSeriesKey, s as readUnit, t as CAP_KEY_PREFIX, u as SeriesRegistry } from "../../capture-engine-DySELkE_.mjs";
3
3
  import { a as FIVE_MINUTES_MS, c as bucketEndOf, i as DAY_MS, l as bucketStartOf, n as RetentionJob, o as HOUR_MS, r as DepartureTracker, s as ROLLUP_GRACE_MS, t as DEFAULT_RETENTION, u as floorTo } from "../../retention-CUOVI1p7.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  //#region src/builtins/device-history/capture/point-writer.ts
@@ -171,18 +171,21 @@ export declare function resolveDevicePresence(deps: BindingsDeps, row: DeviceRow
171
171
  /** "Does the ledger hold any row at all?", asked at most once per pass. */
172
172
  export type LedgerNonEmpty = () => Promise<boolean>;
173
173
  /**
174
- * Does a capability apply to a device of type `deviceType`?
174
+ * Does a capability apply to a device of type `deviceType` and role `role`?
175
175
  *
176
- * The cap's `deviceTypes` is the ONLY declaration consulted (D4: behavioural
177
- * cap metadata lives in the `*.cap.ts`, never in a manifest). Two deliberate
178
- * fail-open cases:
176
+ * The cap's `deviceTypes` and `deviceRoles` are the ONLY declarations
177
+ * consulted (D4: behavioural cap metadata lives in the `*.cap.ts`, never in a
178
+ * manifest). A type the cap's `deviceRoles` names binds only for those roles
179
+ * (D1033: a heater is a switch with role `switch-heater`); the role is read
180
+ * from the row on every pass, so a role change applies with no restart. Two
181
+ * deliberate fail-open cases:
179
182
  *
180
183
  * - a cap that declares no `deviceTypes` (or an empty list) applies to every
181
184
  * device — the pre-existing, back-compatible semantics;
182
185
  * - an UNKNOWN `deviceType` never filters, so a missing/failed meta lookup
183
186
  * changes nothing (D49: a read that fails must not destroy work).
184
187
  */
185
- export declare function capAppliesToDeviceType(def: CapabilityDefinition | undefined, deviceType: string | undefined): boolean;
188
+ export declare function capAppliesToDeviceType(def: CapabilityDefinition | undefined, deviceType: string | undefined, role: string | null | undefined): boolean;
186
189
  /**
187
190
  * An addon's identity, with the node it happens to run on stripped.
188
191
  *
@@ -3,10 +3,10 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-CLnTYKFn.js");
6
+ const require_dist = require("../../dist-LQWK1_M4.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-N7lslQJK.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-BCZeI3eY.js");
10
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
11
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
12
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
@@ -554,6 +554,25 @@ function joinRuntimeBlob(native, owned, policyFor) {
554
554
  return out;
555
555
  }
556
556
  /**
557
+ * `record` with the value at a DOTTED claim path replaced, as a copy: a claim
558
+ * of `oscillationAxes.horizontal.angle` sets that leaf and keeps its siblings.
559
+ * A missing or `null` parent becomes `{}` — the cap schema's leaf defaults
560
+ * fill the rest (an axis the native reports absent, linked in Customize).
561
+ */
562
+ function setPath(record, segments, value) {
563
+ const [head, ...rest] = segments;
564
+ if (head === void 0) return { ...record };
565
+ if (rest.length === 0) return {
566
+ ...record,
567
+ [head]: value
568
+ };
569
+ const child = record[head];
570
+ return {
571
+ ...record,
572
+ [head]: setPath(isPlainRecord(child) ? child : {}, rest, value)
573
+ };
574
+ }
575
+ /**
557
576
  * The one merge. Held when a claimed field has no value yet (S5: never
558
577
  * answered from the native), when a `replace` has no native slice to overlay
559
578
  * (a partial slice is never emitted), or when the merged slice fails the cap's
@@ -569,10 +588,7 @@ function mergeOwned(native, owned, schema) {
569
588
  kind: "held",
570
589
  reason: "no native slice yet"
571
590
  };
572
- const merged = {
573
- ...native,
574
- ...owned.values
575
- };
591
+ const merged = Object.entries(owned.values).reduce((acc, [path, value]) => setPath(acc, path.split("."), value), { ...native });
576
592
  if (schema === null) return {
577
593
  kind: "slice",
578
594
  slice: merged
@@ -1498,22 +1514,22 @@ function onceLedgerNonEmpty(deps) {
1498
1514
  };
1499
1515
  }
1500
1516
  /**
1501
- * Does a capability apply to a device of type `deviceType`?
1517
+ * Does a capability apply to a device of type `deviceType` and role `role`?
1502
1518
  *
1503
- * The cap's `deviceTypes` is the ONLY declaration consulted (D4: behavioural
1504
- * cap metadata lives in the `*.cap.ts`, never in a manifest). Two deliberate
1505
- * fail-open cases:
1519
+ * The cap's `deviceTypes` and `deviceRoles` are the ONLY declarations
1520
+ * consulted (D4: behavioural cap metadata lives in the `*.cap.ts`, never in a
1521
+ * manifest). A type the cap's `deviceRoles` names binds only for those roles
1522
+ * (D1033: a heater is a switch with role `switch-heater`); the role is read
1523
+ * from the row on every pass, so a role change applies with no restart. Two
1524
+ * deliberate fail-open cases:
1506
1525
  *
1507
1526
  * - a cap that declares no `deviceTypes` (or an empty list) applies to every
1508
1527
  * device — the pre-existing, back-compatible semantics;
1509
1528
  * - an UNKNOWN `deviceType` never filters, so a missing/failed meta lookup
1510
1529
  * changes nothing (D49: a read that fails must not destroy work).
1511
1530
  */
1512
- function capAppliesToDeviceType(def, deviceType) {
1513
- if (deviceType === void 0) return true;
1514
- const declared = def?.deviceTypes;
1515
- if (!declared || declared.length === 0) return true;
1516
- return declared.some((t) => t === deviceType);
1531
+ function capAppliesToDeviceType(def, deviceType, role) {
1532
+ return require_dist.capAppliesToDeviceKind(def, deviceType, role);
1517
1533
  }
1518
1534
  /**
1519
1535
  * An addon's identity, with the node it happens to run on stripped.
@@ -1537,13 +1553,13 @@ function addonIdentityOf(addonId) {
1537
1553
  * addon are ONE provider — the defect this exists to make unrepresentable.
1538
1554
  * Gated only by the cap's declared `deviceTypes` (D4), like step 2's auto-bind.
1539
1555
  */
1540
- function collectionBindings(deps, deviceId, deviceType) {
1556
+ function collectionBindings(deps, deviceId, deviceType, role) {
1541
1557
  const registry = deps.capabilityRegistry;
1542
1558
  if (!registry) return [];
1543
1559
  const out = [];
1544
1560
  for (const declared of registry.listCapabilities()) {
1545
1561
  if (declared.mode !== "collection") continue;
1546
- if (!capAppliesToDeviceType(registry.getDefinition(declared.name), deviceType)) continue;
1562
+ if (!capAppliesToDeviceType(registry.getDefinition(declared.name), deviceType, role)) continue;
1547
1563
  const nativeAddonId = registry.getNativeAddonId(declared.name, deviceId);
1548
1564
  const seen = /* @__PURE__ */ new Set();
1549
1565
  for (const addonId of [...declared.providers, ...nativeAddonId ? [nativeAddonId] : []]) {
@@ -1597,10 +1613,11 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1597
1613
  const storeKey = String(deviceId);
1598
1614
  const perDevice = pass.store.deviceBindings[storeKey] ?? {};
1599
1615
  const deviceType = resolveDeviceType(deps, row, deviceId);
1616
+ const deviceRole = row?.meta.role ?? null;
1600
1617
  const presence = await resolveDevicePresence(deps, row, deviceId, pass.ledgerNonEmpty);
1601
1618
  const entries = [];
1602
1619
  const seenCaps = /* @__PURE__ */ new Set();
1603
- const collectionEntries = collectionBindings(deps, deviceId, deviceType);
1620
+ const collectionEntries = collectionBindings(deps, deviceId, deviceType, deviceRole);
1604
1621
  for (const entry of collectionEntries) {
1605
1622
  entries.push(entry);
1606
1623
  seenCaps.add(entry.capName);
@@ -1635,7 +1652,7 @@ async function resolveBindingsForDevice(deps, deviceId, row, pass) {
1635
1652
  const skippedForType = [];
1636
1653
  for (const capName of deps.capabilityRegistry.getCapsWithDefaultWrapper()) {
1637
1654
  if (seenCaps.has(capName)) continue;
1638
- if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType)) {
1655
+ if (!capAppliesToDeviceType(deps.capabilityRegistry.getDefinition(capName), deviceType, deviceRole)) {
1639
1656
  skippedForType.push(capName);
1640
1657
  continue;
1641
1658
  }
@@ -6991,7 +7008,7 @@ async function registerDevice(pctx, input) {
6991
7008
  throw new Error(`[device-manager] registerDevice: device ${id} (${addonId}/${stableId}) was removed — refusing to resurrect it`);
6992
7009
  }
6993
7010
  if (Array.isArray(input.secretConfigPaths)) pctx.secretConfigPaths.set(id, input.secretConfigPaths);
6994
- const { isFirstRegistration, exportFingerprint, fingerprintChanged, storedFeatures, inheritedLocation, inheritedDescendantIds, inheritFailed } = await pctx.metaStore.withMetaWriteLock(async () => {
7011
+ const { isFirstRegistration, exportFingerprint, fingerprintChanged, storedFeatures, inheritedLocation, inheritedDescendantIds, inheritFailed, filledRole } = await pctx.metaStore.withMetaWriteLock(async () => {
6995
7012
  const existingRow = await pctx.metaStore.rows.get(id);
6996
7013
  const existingMeta = existingRow?.meta;
6997
7014
  const wasRegistered = existingRow?.registered ?? false;
@@ -7023,6 +7040,9 @@ async function registerDevice(pctx, input) {
7023
7040
  exportFingerprint: fingerprint
7024
7041
  });
7025
7042
  if (existingMeta?.alias === void 0) await pctx.metaStore.rows.patch(id, { alias: await freeAliasFor(pctx.metaStore.rows, resolvedName, id, await readReservedAliases(pctx)) });
7043
+ const providerRole = typeof input.role === "string" && input.role.length > 0 ? input.role : null;
7044
+ const roleToFill = existingMeta?.role == null ? providerRole : null;
7045
+ if (roleToFill !== null) await pctx.metaStore.rows.patch(id, { role: roleToFill });
7026
7046
  const descendantsFilled = [];
7027
7047
  const descendantsFailed = [];
7028
7048
  if (inherited !== null) for (const descendant of await collectDescendants(pctx.metaStore, id)) {
@@ -7044,9 +7064,30 @@ async function registerDevice(pctx, input) {
7044
7064
  fingerprintChanged: existingMeta?.exportFingerprint !== fingerprint,
7045
7065
  inheritedLocation: inherited,
7046
7066
  inheritedDescendantIds: descendantsFilled,
7047
- inheritFailed: descendantsFailed
7067
+ inheritFailed: descendantsFailed,
7068
+ filledRole: roleToFill
7048
7069
  };
7049
7070
  });
7071
+ if (filledRole !== null) {
7072
+ pctx.host.ctx.eventBus.emit({
7073
+ id: (0, node_crypto.randomUUID)(),
7074
+ timestamp: /* @__PURE__ */ new Date(),
7075
+ source: {
7076
+ type: "device",
7077
+ id
7078
+ },
7079
+ category: require_dist.EventCategory.DeviceMetaChanged,
7080
+ data: {
7081
+ deviceId: id,
7082
+ field: "role",
7083
+ value: filledRole
7084
+ }
7085
+ });
7086
+ pctx.host.ctx.logger.info("registerDevice: filled the missing role from the provider", {
7087
+ tags: { deviceId: id },
7088
+ meta: { role: filledRole }
7089
+ });
7090
+ }
7050
7091
  if (Object.keys(config).length > 0) await pctx.settings.writeDeviceStore(id, config);
7051
7092
  pctx.metaStore.idToAddonId.set(id, addonId);
7052
7093
  if (inheritedLocation !== null) {
@@ -9817,6 +9858,58 @@ var FleetReadCensus = class FleetReadCensus {
9817
9858
  //#endregion
9818
9859
  //#region src/builtins/device-manager/device-row-store.ts
9819
9860
  /**
9861
+ * `device-manager:devices` — ONE ROW PER DEVICE.
9862
+ *
9863
+ * ## What this replaces
9864
+ *
9865
+ * The device-manager used to keep its whole fleet in three JSON blobs on the
9866
+ * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
9867
+ * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
9868
+ * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
9869
+ * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
9870
+ * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
9871
+ * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
9872
+ * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
9873
+ * through the meta store, and every runner's first store read queued behind it.
9874
+ *
9875
+ * Writing was worse than reading. `ConfigManager.createSettingsView`'s
9876
+ * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
9877
+ * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
9878
+ * camera rewrote 625 KB.
9879
+ *
9880
+ * A row per device makes the per-device question a primary-key lookup and the
9881
+ * per-device write a single-row upsert touching only the columns named.
9882
+ *
9883
+ * ## Why `deviceIndex` has no column and no collection
9884
+ *
9885
+ * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
9886
+ * and `stableId` are fields of every row, so "this addon's devices" is
9887
+ * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
9888
+ * membership meant "`registerDevice` has run at least once", which is how
9889
+ * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
9890
+ * meta refresh. `allocateDeviceId` writes a row without registering, so row
9891
+ * existence alone cannot answer it. That bit is the {@link registered} column,
9892
+ * and nothing else of `deviceIndex` survives.
9893
+ *
9894
+ * ## Why metadata is a column and not a second collection
9895
+ *
9896
+ * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
9897
+ * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
9898
+ * had to preserve a `metadata` field would eventually clobber a concurrent
9899
+ * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
9900
+ * problem — `set` names its columns and leaves the rest of the row untouched —
9901
+ * so the split has no reason to exist and metadata rides on the device's own
9902
+ * row.
9903
+ *
9904
+ * ## Adding a column later
9905
+ *
9906
+ * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
9907
+ * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
9908
+ * to a populated table, so the backend counts it as non-additive and REBUILDS
9909
+ * the collection — dropping every row. Any column added here after ship must
9910
+ * either be nullable or carry a `defaultValue`.
9911
+ */
9912
+ /**
9820
9913
  * @durable class=ledger owner=device-manager
9821
9914
  * write="one row per device, written by `allocateDeviceId` (identity placeholder),
9822
9915
  * `registerDevice` (full reconcile) and every meta setter (single-column patch);
@@ -10056,7 +10149,8 @@ function decodeDeviceRow(data) {
10056
10149
  const deviceId = readNumber(data["deviceId"]);
10057
10150
  const addonId = readString(data["addonId"]);
10058
10151
  const stableId = readString(data["stableId"]);
10059
- const type = readString(data["type"]);
10152
+ const storedType = readString(data["type"]);
10153
+ const type = storedType === void 0 ? void 0 : require_dist.canonicalStoredDeviceType(storedType);
10060
10154
  const name = readString(data["name"]);
10061
10155
  if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
10062
10156
  const location = readString(data["location"]);