@camstack/server 1.2.927 → 1.2.929

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 (235) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +11 -14
  3. package/system/dist/addon-id-CVg1_r5E.mjs +39 -0
  4. package/system/dist/addon-id-Di0lNJ89.js +50 -0
  5. package/system/dist/addon-pages.cap-Df9FQwN1.js +49 -0
  6. package/system/dist/addon-pages.cap-DksUlE8j.mjs +44 -0
  7. package/system/dist/addon-settings.cap-3-TIIMq_.mjs +592 -0
  8. package/system/dist/addon-settings.cap-DAiE0Nb0.js +651 -0
  9. package/system/dist/addon-widgets.cap-C4jxflbF.js +200 -0
  10. package/system/dist/addon-widgets.cap-D9m48X78.mjs +183 -0
  11. package/system/dist/base-addon-DD5dIfcZ.js +4624 -0
  12. package/system/dist/base-addon-Md14i7pe.mjs +4505 -0
  13. package/system/dist/base-device-2sL1DMm1.js +1103 -0
  14. package/system/dist/base-device-IuM1AwXZ.mjs +1098 -0
  15. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +8 -6
  16. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +3 -1
  17. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +8 -6
  18. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +3 -1
  19. package/system/dist/builtins/alerts/alerts.addon.js +113 -56
  20. package/system/dist/builtins/alerts/alerts.addon.mjs +58 -1
  21. package/system/dist/builtins/autotrack/index.js +21 -17
  22. package/system/dist/builtins/autotrack/index.mjs +5 -1
  23. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +14 -11
  24. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -2
  25. package/system/dist/builtins/calendars/calendars.addon.js +8 -6
  26. package/system/dist/builtins/calendars/calendars.addon.mjs +3 -1
  27. package/system/dist/builtins/camera-grid/index.js +615 -58
  28. package/system/dist/builtins/camera-grid/index.mjs +558 -1
  29. package/system/dist/builtins/composer/composer.addon.js +788 -209
  30. package/system/dist/builtins/composer/composer.addon.mjs +583 -4
  31. package/system/dist/builtins/console-logging/index.js +4 -3
  32. package/system/dist/builtins/console-logging/index.mjs +2 -1
  33. package/system/dist/builtins/core-blocks/core-blocks.addon.js +7887 -381
  34. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +7511 -5
  35. package/system/dist/builtins/core-notifier/core-notifier.addon.js +731 -21
  36. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +711 -1
  37. package/system/dist/builtins/device-history/device-history.addon.js +110 -31
  38. package/system/dist/builtins/device-history/device-history.addon.mjs +81 -2
  39. package/system/dist/builtins/device-manager/device-manager.addon.js +12806 -227
  40. package/system/dist/builtins/device-manager/device-manager.addon.mjs +12583 -5
  41. package/system/dist/builtins/hub-forwarder/index.js +4 -3
  42. package/system/dist/builtins/hub-forwarder/index.mjs +2 -1
  43. package/system/dist/builtins/keychain/index.js +31 -28
  44. package/system/dist/builtins/keychain/index.mjs +7 -4
  45. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +15 -12
  46. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +4 -1
  47. package/system/dist/builtins/local-auth/local-auth.addon.js +140 -39
  48. package/system/dist/builtins/local-auth/local-auth.addon.mjs +103 -3
  49. package/system/dist/builtins/local-network/local-network.addon.js +43 -39
  50. package/system/dist/builtins/local-network/local-network.addon.mjs +7 -3
  51. package/system/dist/builtins/loki-logging/index.js +23 -17
  52. package/system/dist/builtins/loki-logging/index.mjs +7 -1
  53. package/system/dist/builtins/native-metrics/native-metrics.addon.js +156 -15
  54. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +142 -1
  55. package/system/dist/builtins/platform-probe/index.js +25 -23
  56. package/system/dist/builtins/platform-probe/index.mjs +4 -2
  57. package/system/dist/builtins/record-entries/index.js +9 -7
  58. package/system/dist/builtins/record-entries/index.mjs +3 -1
  59. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +4 -4
  60. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  61. package/system/dist/builtins/snapshot/index.js +97 -44
  62. package/system/dist/builtins/snapshot/index.mjs +54 -1
  63. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +5 -4
  64. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +2 -1
  65. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  66. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  67. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +87 -61
  68. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +29 -3
  69. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +81 -72
  70. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +10 -1
  71. package/system/dist/builtins/system-config/system-config.addon.js +17 -14
  72. package/system/dist/builtins/system-config/system-config.addon.mjs +6 -3
  73. package/system/dist/builtins/winston-logging/index.js +7 -5
  74. package/system/dist/builtins/winston-logging/index.mjs +3 -1
  75. package/system/dist/calendars.cap-CaFlShS9.js +155 -0
  76. package/system/dist/calendars.cap-_C4eD4fi.mjs +138 -0
  77. package/system/dist/camstack-error-DJ-TUAi1.js +23 -0
  78. package/system/dist/camstack-error-viZYfcj9.mjs +18 -0
  79. package/system/dist/cap-call-context-Bd76CbOW.js +95 -0
  80. package/system/dist/cap-call-context-DNwdgGSQ.mjs +78 -0
  81. package/system/dist/capability-definition-C2rJdVeX.mjs +177 -0
  82. package/system/dist/capability-definition-HCmTem8c.js +242 -0
  83. package/system/dist/{capture-engine-BcuwOSXv.js → capture-engine-DZ0LIUqA.js} +5 -4
  84. package/system/dist/{capture-engine-Bz7eXFjT.mjs → capture-engine-DiwbjoWp.mjs} +2 -1
  85. package/system/dist/command-origin-claim-Cief660O.js +35 -0
  86. package/system/dist/command-origin-claim-D1Wy7Qld.mjs +24 -0
  87. package/system/dist/composition-sources-Caqv7O7z.mjs +391 -0
  88. package/system/dist/composition-sources-CgnHjm8Q.js +408 -0
  89. package/system/dist/{constants-D2etJ02O.js → constants-Ba3FTIHl.js} +1 -1
  90. package/system/dist/constants-C860Y6U4.js +26 -0
  91. package/system/dist/{constants-BcUTQd1M.mjs → constants-DB4piTD5.mjs} +1 -1
  92. package/system/dist/constants-DCLpoF4L.mjs +21 -0
  93. package/system/dist/coral-accelerators-7o8hqvcN.js +564 -0
  94. package/system/dist/coral-accelerators-BKcXP59c.mjs +521 -0
  95. package/system/dist/core-blocks.cap-C6iKAZ-x.mjs +17986 -0
  96. package/system/dist/core-blocks.cap-LEMqVwxO.js +18705 -0
  97. package/system/dist/custom-actions-BFUSalC9.mjs +25 -0
  98. package/system/dist/custom-actions-D92NRi2c.js +36 -0
  99. package/system/dist/database-snapshot.cap-DF38e-0P.js +162 -0
  100. package/system/dist/database-snapshot.cap-dhrc9xnY.mjs +133 -0
  101. package/system/dist/declared-device-BWphj9WE.js +303 -0
  102. package/system/dist/declared-device-CKERA1Hi.mjs +286 -0
  103. package/system/dist/{device-ca-ExMN3xW3.mjs → device-ca-BLM6fccc.mjs} +2 -1
  104. package/system/dist/{device-ca-CU8zh9Pi.js → device-ca-C5kJE6mL.js} +7 -6
  105. package/system/dist/device-certificate-Cddm4Idn.mjs +91 -0
  106. package/system/dist/device-certificate-CguVACQO.js +162 -0
  107. package/system/dist/device-identifiers-BQg9EQi1.js +600 -0
  108. package/system/dist/device-identifiers-iSuQCKmK.mjs +529 -0
  109. package/system/dist/device-kind-BJ2pfsjw.mjs +78 -0
  110. package/system/dist/device-kind-CsSiv_YF.js +101 -0
  111. package/system/dist/device-manager.cap-2abwVLCM.js +2874 -0
  112. package/system/dist/device-manager.cap-CFZSPfUh.mjs +2749 -0
  113. package/system/dist/device-provider.cap-3Uvk6f5-.mjs +331 -0
  114. package/system/dist/device-provider.cap-D7TV2kVH.js +366 -0
  115. package/system/dist/{device-row-store-CeW_GWh9.mjs → device-row-store-YF3jtmkk.mjs} +4 -1
  116. package/system/dist/{device-row-store-BMIR-n3m.js → device-row-store-doTfMOqn.js} +12 -9
  117. package/system/dist/device-transitions.cap-B5w5PYU_.js +860 -0
  118. package/system/dist/device-transitions.cap-DojcwEuX.mjs +819 -0
  119. package/system/dist/device-type-CbQsnFdC.js +477 -0
  120. package/system/dist/device-type-DgEvK3ch.mjs +454 -0
  121. package/system/dist/entry-kind-D9MuVJCK.mjs +44 -0
  122. package/system/dist/entry-kind-cq90c--V.js +55 -0
  123. package/system/dist/error.cap-CSM_SRfR.mjs +3423 -0
  124. package/system/dist/error.cap-DBhgPeWK.js +3848 -0
  125. package/system/dist/file-host-worker.js +1 -1
  126. package/system/dist/file-host-worker.mjs +1 -1
  127. package/system/dist/history-catalog-BKRarIL_.js +831 -0
  128. package/system/dist/history-catalog-BwTeQ4Mr.mjs +802 -0
  129. package/system/dist/{hub-identity-Csxx2Q8k.js → hub-identity-BMdR3Mw9.js} +2 -2
  130. package/system/dist/{hub-identity-BBXzP6Ve.mjs → hub-identity-DjMN9Ac2.mjs} +1 -1
  131. package/system/dist/{hub-mdns-ciao-By5577HM.js → hub-mdns-ciao--0v1TKME.js} +5 -5
  132. package/system/dist/{hub-mdns-ciao-DG17NbGU.mjs → hub-mdns-ciao-DBrtHOcc.mjs} +2 -2
  133. package/system/dist/index.js +763 -151
  134. package/system/dist/index.mjs +624 -12
  135. package/system/dist/integration-instances.cap-Cl9O-k4h.mjs +538 -0
  136. package/system/dist/integration-instances.cap-dJIxg2_s.js +549 -0
  137. package/system/dist/keychain-admin.cap-Db_oFX4H.js +425 -0
  138. package/system/dist/keychain-admin.cap-GtM7gVGG.mjs +396 -0
  139. package/system/dist/l10n-Bu6aUvSY.mjs +10 -0
  140. package/system/dist/l10n-CGMvp7NF.js +15 -0
  141. package/system/dist/labels-DX5S8deC.js +81 -0
  142. package/system/dist/labels-DsBcU7md.mjs +64 -0
  143. package/system/dist/{legacy-integration-rows-door-CVwOo5aq.js → legacy-integration-rows-door-B1nzxxr5.js} +2 -2
  144. package/system/dist/{legacy-integration-rows-door-D9tQOUzh.mjs → legacy-integration-rows-door-nTvo_6jQ.mjs} +1 -1
  145. package/system/dist/log-destination.cap-CxZzAVaR.mjs +143 -0
  146. package/system/dist/log-destination.cap-DELPJkZ0.js +148 -0
  147. package/system/dist/low-power-sleep.cap-7lfVU41N.js +103 -0
  148. package/system/dist/low-power-sleep.cap-tGPmaZ_V.mjs +92 -0
  149. package/system/dist/mask-shape-Ci8Co9w0.mjs +57 -0
  150. package/system/dist/mask-shape-CmPA2fst.js +92 -0
  151. package/system/dist/metrics-provider.cap-BNmcHDkQ.mjs +405 -0
  152. package/system/dist/metrics-provider.cap-BcmQUt6l.js +410 -0
  153. package/system/dist/migration-BMjgkyG2.js +380 -0
  154. package/system/dist/migration-DRJAtdy7.mjs +321 -0
  155. package/system/dist/network-access.cap-B5TWLDCC.js +1099 -0
  156. package/system/dist/network-access.cap-BJnGbE6n.mjs +1004 -0
  157. package/system/dist/notification-rules.cap-B__YBgnG.js +3422 -0
  158. package/system/dist/notification-rules.cap-D9ArZlwx.mjs +3357 -0
  159. package/system/dist/ops-log-CB4pIdqi.mjs +64 -0
  160. package/system/dist/ops-log-pxt9176Z.js +81 -0
  161. package/system/dist/pinned-binary-BOhOSNff.js +28 -0
  162. package/system/dist/pinned-binary-CrIRAi4G.mjs +23 -0
  163. package/system/dist/platform-probe.cap-1WrMhWHx.js +250 -0
  164. package/system/dist/platform-probe.cap-BFeqFLtQ.mjs +233 -0
  165. package/system/dist/prefix-walk-B4b2-9aK.mjs +790 -0
  166. package/system/dist/prefix-walk-DC0ljmbB.js +843 -0
  167. package/system/dist/ptz-autotrack.cap-BW7w0zHD.js +229 -0
  168. package/system/dist/ptz-autotrack.cap-DT2GypXw.mjs +224 -0
  169. package/system/dist/quantity-D3g5SxsZ.mjs +114 -0
  170. package/system/dist/quantity-lY1KiTSZ.js +143 -0
  171. package/system/dist/raw-secret-migration-DxuBFtvi.js +50 -0
  172. package/system/dist/raw-secret-migration-iv88mLoc.mjs +39 -0
  173. package/system/dist/record-entries.cap-sMUhTvTU.mjs +75 -0
  174. package/system/dist/record-entries.cap-ti1C046R.js +80 -0
  175. package/system/dist/record-kind-DoBfYHCs.js +203 -0
  176. package/system/dist/record-kind-ub6NXqfh.mjs +162 -0
  177. package/system/dist/recording-archive.cap-7OrIn9e5.mjs +1299 -0
  178. package/system/dist/recording-archive.cap-D7bo-QSM.js +1328 -0
  179. package/system/dist/records.cap-ClcWV64i.js +329 -0
  180. package/system/dist/records.cap-CwLT2ByG.mjs +294 -0
  181. package/system/dist/relocate-CdVQAk-w.js +804 -0
  182. package/system/dist/relocate-CoZZTui1.mjs +661 -0
  183. package/system/dist/rename-composition-block-7WIICIDq.mjs +33525 -0
  184. package/system/dist/rename-composition-block-CcWLwVhG.js +34692 -0
  185. package/system/dist/{restore-archive-kwtBd00M.mjs → restore-archive-CjAyKpgX.mjs} +3 -1
  186. package/system/dist/{restore-archive-CIFvqOze.js → restore-archive-CkTkv3Ss.js} +6 -4
  187. package/system/dist/scoped-settings-CylSSq_8.js +955 -0
  188. package/system/dist/scoped-settings-DVWUIP7Z.mjs +650 -0
  189. package/system/dist/server-name-BIhLuHvX.mjs +35 -0
  190. package/system/dist/server-name-OALNvpqC.js +52 -0
  191. package/system/dist/settings-store.cap-Ci4F2zul.mjs +569 -0
  192. package/system/dist/settings-store.cap-wlJhCspr.js +640 -0
  193. package/system/dist/snapshot.cap-3suPdBHV.js +250 -0
  194. package/system/dist/snapshot.cap-Bs8Oyaqh.mjs +245 -0
  195. package/system/dist/source-info-DGB7SdB_.mjs +190 -0
  196. package/system/dist/source-info-DtWf4k2j.js +225 -0
  197. package/system/dist/storage-admin.cap-BSv1NjKJ.mjs +883 -0
  198. package/system/dist/storage-admin.cap-he0OqvVM.js +906 -0
  199. package/system/dist/storage-location-CBT8GCD6.mjs +163 -0
  200. package/system/dist/storage-location-CTweDMZf.js +198 -0
  201. package/system/dist/storage-location-mode-B21UVRRX.mjs +167 -0
  202. package/system/dist/storage-location-mode-CS4sMzo-.js +232 -0
  203. package/system/dist/storage-migration.cap-CyyATY_p.js +330 -0
  204. package/system/dist/storage-migration.cap-D7QqGobp.mjs +313 -0
  205. package/system/dist/storage-occupancy.cap-2rmnS58Z.js +622 -0
  206. package/system/dist/storage-occupancy.cap-CqBztTl9.mjs +611 -0
  207. package/system/dist/storage-provider.cap-Bw0CfxVc.js +213 -0
  208. package/system/dist/storage-provider.cap-CMeck2w4.mjs +202 -0
  209. package/system/dist/stream-catalog.cap-Bp7SkgIf.mjs +6560 -0
  210. package/system/dist/stream-catalog.cap-D3uwePiA.js +6763 -0
  211. package/system/dist/streaming-shared-B8cXatuU.mjs +431 -0
  212. package/system/dist/streaming-shared-DQwFZOSi.js +526 -0
  213. package/system/dist/system-reasons-Be_k1W8g.js +25 -0
  214. package/system/dist/system-reasons-CYj4qwyS.mjs +20 -0
  215. package/system/dist/tag-BxLazvVb.js +2138 -0
  216. package/system/dist/tag-uZBAq6ox.mjs +2073 -0
  217. package/system/dist/user-management.cap-B9QDu8NE.js +825 -0
  218. package/system/dist/user-management.cap-DBIi77sB.mjs +766 -0
  219. package/system/dist/vector-store.cap-DnyfrYDn.js +330 -0
  220. package/system/dist/vector-store.cap-h2GHWQ1t.mjs +319 -0
  221. package/system/dist/{wal-maintenance-CTrCPzds.mjs → wal-maintenance-BG01rOn9.mjs} +0 -0
  222. package/system/dist/{wal-maintenance-dq7T3quB.js → wal-maintenance-DyrebYKF.js} +0 -0
  223. package/system/dist/zod-secret-DS7mj1bk.js +78 -0
  224. package/system/dist/zod-secret-zY4nM61M.mjs +73 -0
  225. package/system/package.json +1 -1
  226. package/system/dist/composition-sources-BI614LJx.mjs +0 -141
  227. package/system/dist/composition-sources-v_kkb8A9.js +0 -152
  228. package/system/dist/coral-accelerators-BSVsBVzt.js +0 -250
  229. package/system/dist/coral-accelerators-DBlgWB8k.mjs +0 -231
  230. package/system/dist/dist-BCHMSqzc.mjs +0 -143467
  231. package/system/dist/dist-BZfvhfS1.js +0 -146970
  232. package/system/dist/prefix-walk-DAOBSyH1.mjs +0 -88
  233. package/system/dist/prefix-walk-Dv6MLZlM.js +0 -99
  234. package/system/dist/rename-composition-block-C9HuBrKS.js +0 -112
  235. package/system/dist/rename-composition-block-DtaYmYAR.mjs +0 -101
@@ -0,0 +1,1098 @@
1
+ import { C as featureProbeCapability, T as deviceStatusCapability } from "./stream-catalog.cap-Bp7SkgIf.mjs";
2
+ import { p as createEvent } from "./base-addon-Md14i7pe.mjs";
3
+ import { Z as errMsg } from "./scoped-settings-DVWUIP7Z.mjs";
4
+ import { t as collectZodSecretPaths } from "./zod-secret-zY4nM61M.mjs";
5
+ import { a as isEmptyIdentifiers, s as normaliseIdentifiers, t as DEVICE_IDENTIFIER_KEYS } from "./device-identifiers-iSuQCKmK.mjs";
6
+ import { n as ERROR_STATUS_COLD, r as errorCapability } from "./error.cap-CSM_SRfR.mjs";
7
+ import { i as mergeSourceInfo, o as synthesizeSourceInfo, r as extractSourceInfoFromMetadata, t as SOURCE_INFO_METADATA_KEY } from "./source-info-DGB7SdB_.mjs";
8
+ //#region ../types/dist/esm/device/device-config.mjs
9
+ var DeviceConfig = class DeviceConfig {
10
+ schema;
11
+ data;
12
+ persistFn;
13
+ constructor(schema, data, persist) {
14
+ this.schema = schema;
15
+ this.data = data;
16
+ this.persistFn = persist;
17
+ }
18
+ /**
19
+ * Build a `DeviceConfig` from a persisted blob, with automatic
20
+ * recovery from schema-validation failures. Boot must never be
21
+ * blocked by stale persisted values: if Zod rejects the blob,
22
+ * we drop every offending top-level field, retry, and persist
23
+ * the cleaned blob so the bad value is healed in the DB on next
24
+ * write. The most common trigger is a tightened range constraint
25
+ * (e.g. `max(100) → max(50)`) on a field that already has an
26
+ * out-of-range value persisted from the previous schema. Without
27
+ * this safety net, the device would fail to instantiate and end
28
+ * up with no caps registered — exactly the failure mode that
29
+ * stranded device 15 when `motionSensitivity: 90` no longer fit
30
+ * the new `1..50` schema.
31
+ *
32
+ * Recovery rules:
33
+ * 1. Try `safeParse(initialData)`. If it succeeds, done.
34
+ * 2. On failure, walk `error.issues`, collect the top-level path
35
+ * of each issue, and drop those keys from `initialData`.
36
+ * 3. Re-run `safeParse`. If the cleaned blob now passes (Zod
37
+ * fills the missing keys with schema defaults / undefined for
38
+ * `.optional()`), persist it via `persist()` so the bad
39
+ * values disappear from the DB, and return the device.
40
+ * 4. If the cleaned blob STILL fails (very rare — would require
41
+ * a non-recoverable required field), fall back to
42
+ * `schema.parse({})` so the device still boots with pure
43
+ * schema defaults. Persist nothing in that path so the next
44
+ * successful `setAll` still writes a coherent blob.
45
+ */
46
+ static fromSchema(schema, persist, initialData = {}, onRecover) {
47
+ const first = schema.safeParse(initialData);
48
+ if (first.success) return new DeviceConfig(schema, first.data, persist);
49
+ const droppedKeys = /* @__PURE__ */ new Set();
50
+ for (const issue of first.error.issues) {
51
+ const top = issue.path[0];
52
+ if (typeof top === "string") droppedKeys.add(top);
53
+ }
54
+ const cleaned = { ...initialData };
55
+ for (const k of droppedKeys) delete cleaned[k];
56
+ const second = schema.safeParse(cleaned);
57
+ onRecover?.({
58
+ droppedKeys: [...droppedKeys],
59
+ issues: first.error.issues
60
+ });
61
+ if (second.success) {
62
+ persist(second.data).catch(() => {});
63
+ return new DeviceConfig(schema, second.data, persist);
64
+ }
65
+ return new DeviceConfig(schema, schema.parse({}), persist);
66
+ }
67
+ get values() {
68
+ return this.data;
69
+ }
70
+ get(key) {
71
+ return this.data[key];
72
+ }
73
+ async set(key, value) {
74
+ const next = this.schema.parse({
75
+ ...this.data,
76
+ [key]: value
77
+ });
78
+ this.data = next;
79
+ await this.persistFn(this.data);
80
+ }
81
+ /**
82
+ * Merge an untyped patch onto the current config and persist. Accepts
83
+ * `Record<string, unknown>` because the patch typically comes from the
84
+ * UI form layer (a `ConfigField.key → value` map) where the caller
85
+ * doesn't hold the Zod schema's static type. Runtime validation is
86
+ * authoritative: `this.schema.parse` rejects unknown keys or invalid
87
+ * shapes before touching storage.
88
+ */
89
+ async setAll(partial) {
90
+ const next = this.schema.parse({
91
+ ...this.data,
92
+ ...partial
93
+ });
94
+ this.data = next;
95
+ await this.persistFn(this.data);
96
+ }
97
+ async deleteKey(key) {
98
+ const { [key]: _, ...rest } = this.data;
99
+ const next = this.schema.parse(rest);
100
+ this.data = next;
101
+ await this.persistFn(this.data);
102
+ }
103
+ entries() {
104
+ const shape = this.schema.shape;
105
+ return Object.entries(shape).map(([key, fieldSchema]) => ({
106
+ key,
107
+ schema: fieldSchema,
108
+ value: this.data[key],
109
+ description: fieldSchema.description
110
+ }));
111
+ }
112
+ };
113
+ //#endregion
114
+ //#region ../types/dist/esm/device/device-runtime-state.mjs
115
+ var DeviceRuntimeState = class DeviceRuntimeState {
116
+ writer;
117
+ onWriteFailed;
118
+ /** In-flight writer promises tracked so `flush()` can await them. */
119
+ pendingWrites = /* @__PURE__ */ new Set();
120
+ /**
121
+ * Caps whose last write the hub refused. The equality gate in
122
+ * `applyCapWrite` is bypassed for these, so the SAME value is re-sent on the
123
+ * next write instead of being swallowed forever; a landing write clears it.
124
+ */
125
+ failedWrites = /* @__PURE__ */ new Set();
126
+ /** Per-cap committed slice — after schema validation when known. */
127
+ slices;
128
+ /** Per-cap registered schema (set by `installCapSchema`). */
129
+ schemas = /* @__PURE__ */ new Map();
130
+ listeners = /* @__PURE__ */ new Set();
131
+ capListeners = /* @__PURE__ */ new Map();
132
+ constructor(initial, writer, onWriteFailed) {
133
+ this.writer = writer;
134
+ this.onWriteFailed = onWriteFailed;
135
+ this.slices = /* @__PURE__ */ new Map();
136
+ for (const [k, v] of Object.entries(initial)) if (v && typeof v === "object" && !Array.isArray(v)) this.slices.set(k, { ...v });
137
+ }
138
+ static fromInitial(initial, writer, onWriteFailed) {
139
+ return new DeviceRuntimeState(initial, writer, onWriteFailed);
140
+ }
141
+ installCapSchema(capName, schema) {
142
+ const existing = this.schemas.get(capName);
143
+ if (existing) {
144
+ if (existing !== schema) throw new Error(`[DeviceRuntimeState] capability "${capName}" registered a different runtime-state schema; each cap must declare ONE shape across every provider`);
145
+ return;
146
+ }
147
+ this.schemas.set(capName, schema);
148
+ const stored = this.slices.get(capName);
149
+ if (stored) {
150
+ const result = schema.safeParse(stored);
151
+ if (result.success) this.slices.set(capName, result.data);
152
+ else this.slices.delete(capName);
153
+ }
154
+ }
155
+ getCapState(capName) {
156
+ const slice = this.slices.get(capName);
157
+ if (!slice) return void 0;
158
+ return Object.freeze({ ...slice });
159
+ }
160
+ getCapField(capName, key) {
161
+ return this.slices.get(capName)?.[key];
162
+ }
163
+ setCapState(capName, value) {
164
+ this.applyCapWrite(capName, value, false);
165
+ }
166
+ patchCapState(capName, partial) {
167
+ this.applyCapWrite(capName, partial, true);
168
+ }
169
+ /**
170
+ * Internal worker. `merge` controls whether `value` replaces or
171
+ * shallow-merges into the existing slice. Schema validation runs
172
+ * on the FINAL composed object regardless.
173
+ */
174
+ applyCapWrite(capName, value, merge) {
175
+ const schema = this.schemas.get(capName);
176
+ if (!schema) throw new Error(`[DeviceRuntimeState] no schema registered for cap "${capName}" — did the device register it via ctx.registerNativeCap before writing?`);
177
+ const current = this.slices.get(capName) ?? {};
178
+ const next = merge ? {
179
+ ...current,
180
+ ...value
181
+ } : { ...value };
182
+ const parsed = schema.parse(next);
183
+ if (shallowEqual(current, parsed) && !this.failedWrites.has(capName)) return;
184
+ this.slices.set(capName, parsed);
185
+ this.fireListeners([capName]);
186
+ const writePromise = this.writer(capName, { ...parsed }).then(() => {
187
+ this.failedWrites.delete(capName);
188
+ }).catch((err) => {
189
+ this.failedWrites.add(capName);
190
+ this.onWriteFailed?.(capName, err instanceof Error ? err.message : String(err));
191
+ });
192
+ this.pendingWrites.add(writePromise);
193
+ writePromise.finally(() => {
194
+ this.pendingWrites.delete(writePromise);
195
+ });
196
+ }
197
+ fireListeners(changed) {
198
+ const snap = this.snapshot();
199
+ for (const cb of this.listeners) try {
200
+ cb(changed, snap);
201
+ } catch {}
202
+ for (const capName of changed) {
203
+ const subs = this.capListeners.get(capName);
204
+ if (!subs) continue;
205
+ const slice = this.getCapState(capName);
206
+ for (const cb of subs) try {
207
+ cb(slice);
208
+ } catch {}
209
+ }
210
+ }
211
+ subscribe(cb) {
212
+ this.listeners.add(cb);
213
+ return () => {
214
+ this.listeners.delete(cb);
215
+ };
216
+ }
217
+ subscribeCap(capName, cb) {
218
+ let subs = this.capListeners.get(capName);
219
+ if (!subs) {
220
+ subs = /* @__PURE__ */ new Set();
221
+ this.capListeners.set(capName, subs);
222
+ }
223
+ const adapter = (slice) => {
224
+ cb(slice);
225
+ };
226
+ subs.add(adapter);
227
+ return () => {
228
+ const set = this.capListeners.get(capName);
229
+ if (!set) return;
230
+ set.delete(adapter);
231
+ if (set.size === 0) this.capListeners.delete(capName);
232
+ };
233
+ }
234
+ snapshot() {
235
+ const out = {};
236
+ for (const [k, v] of this.slices) out[k] = Object.freeze({ ...v });
237
+ return Object.freeze(out);
238
+ }
239
+ async flush() {
240
+ if (this.pendingWrites.size === 0) return;
241
+ const inflight = [...this.pendingWrites];
242
+ await Promise.allSettled(inflight);
243
+ }
244
+ };
245
+ function shallowEqual(a, b) {
246
+ const ak = Object.keys(a);
247
+ const bk = Object.keys(b);
248
+ if (ak.length !== bk.length) return false;
249
+ for (const k of ak) if (a[k] !== b[k]) return false;
250
+ return true;
251
+ }
252
+ //#endregion
253
+ //#region ../types/dist/esm/device/declare-identifiers.mjs
254
+ /**
255
+ * Normalise `raw` and declare it: every kind it carries replaces the stored one,
256
+ * every kind it lacks is removed, except the kinds in `options.unread` (a failed
257
+ * read keeps what was stored) — pass everything the provider read in one call.
258
+ */
259
+ async function declareDeviceIdentifiers(deps, raw, options = {}) {
260
+ const { deviceId, logger, writer } = deps;
261
+ const { unread, ...normaliseOptions } = options;
262
+ const { identifiers, rejected } = normaliseIdentifiers(raw, normaliseOptions);
263
+ for (const r of rejected) logger.warn("identifier refused — not declared", {
264
+ tags: { deviceId },
265
+ meta: {
266
+ key: r.key,
267
+ value: r.value,
268
+ reason: r.reason
269
+ }
270
+ });
271
+ const unreadKinds = new Set(unread ?? []);
272
+ if (isEmptyIdentifiers(identifiers) && DEVICE_IDENTIFIER_KEYS.every((key) => unreadKinds.has(key))) {
273
+ logger.debug("no identifier read — nothing declared", { tags: { deviceId } });
274
+ return {
275
+ outcome: "nothing-to-declare",
276
+ identifiers
277
+ };
278
+ }
279
+ if (writer === void 0) {
280
+ logger.warn("identifiers not declared — device-manager unreachable", { tags: { deviceId } });
281
+ return {
282
+ outcome: "unavailable",
283
+ identifiers
284
+ };
285
+ }
286
+ try {
287
+ await writer.mutate({
288
+ deviceId,
289
+ identifiers,
290
+ ...unread !== void 0 && unread.length > 0 ? { unread } : {}
291
+ });
292
+ return {
293
+ outcome: "declared",
294
+ identifiers
295
+ };
296
+ } catch (err) {
297
+ logger.warn("identifiers not declared — setIdentifiers failed", {
298
+ tags: { deviceId },
299
+ meta: { error: errMsg(err) }
300
+ });
301
+ return {
302
+ outcome: "failed",
303
+ identifiers
304
+ };
305
+ }
306
+ }
307
+ //#endregion
308
+ //#region ../types/dist/esm/device/device-error-episode.mjs
309
+ /**
310
+ * The edge between two readings, or `null` for no edge.
311
+ *
312
+ * - `null`/cold → `true` is a START (a fault already open at boot is one);
313
+ * - `true` → `false` is a RESOLVE;
314
+ * - an UNKNOWN reading (`active: null`) is never an edge, in either direction —
315
+ * a failed read must neither raise nor close an episode (D393, D49);
316
+ * - `true` → `true` is the same episode, whatever the code did.
317
+ */
318
+ function deviceErrorEdge(previous, next) {
319
+ if (next.active === true && previous?.active !== true) return "start";
320
+ if (next.active === false && previous?.active === true) return "resolve";
321
+ return null;
322
+ }
323
+ function deviceErrorAlertId(deviceId) {
324
+ return `device-error:${String(deviceId)}`;
325
+ }
326
+ /** Every active fault, the principal first; a status that lists none still names its principal. */
327
+ function activeFaults(status) {
328
+ if (status.faults !== void 0 && status.faults.length > 0) return status.faults.map(({ code, label, severity }) => ({
329
+ code,
330
+ label,
331
+ severity
332
+ }));
333
+ if (status.code === null) return [];
334
+ return [{
335
+ code: status.code,
336
+ label: status.label ?? status.code,
337
+ severity: status.severity
338
+ }];
339
+ }
340
+ /** The alert that opens an episode. `since` is the fault's own start, else `now`. */
341
+ function buildDeviceErrorAlert(deviceId, deviceName, status, now) {
342
+ const label = status.label ?? status.code ?? "Fault";
343
+ const startedAt = status.since ?? now;
344
+ const alertId = deviceErrorAlertId(deviceId);
345
+ return {
346
+ id: alertId,
347
+ category: "device.error",
348
+ severity: "critical",
349
+ title: `${deviceName}: ${label}`,
350
+ message: `${deviceName} reports a fault: ${label}.`,
351
+ action: {
352
+ label: "Open device",
353
+ href: `/devices/${String(deviceId)}`,
354
+ navigation: "app"
355
+ },
356
+ status: "active",
357
+ read: false,
358
+ createdAt: now,
359
+ updatedAt: now,
360
+ source: {
361
+ type: "device",
362
+ id: String(deviceId)
363
+ },
364
+ metadata: {
365
+ episodeId: `${alertId}@${String(startedAt)}`,
366
+ code: status.code,
367
+ deviceSeverity: status.severity,
368
+ label: status.label,
369
+ faults: activeFaults(status)
370
+ }
371
+ };
372
+ }
373
+ //#endregion
374
+ //#region ../types/dist/esm/generated/device-local-state.mjs
375
+ /**
376
+ * Runtime registry: cap-property-name → cap NAME. `BaseDevice`'s `state`
377
+ * getter looks the name up here to construct a slice proxy lazily on first
378
+ * access; the proxy reads only `cap.name`. Names, not definitions, so this file
379
+ * pulls no schema into a bundle (guard `check-device-local-state-schema-free`,
380
+ * D1074). Generated alongside the type so type and registry can never drift apart.
381
+ */
382
+ var DEVICE_LOCAL_STATE_CAP_NAMES = {
383
+ airQualitySensor: "air-quality-sensor",
384
+ alarmPanel: "alarm-panel",
385
+ ambientLightSensor: "ambient-light-sensor",
386
+ audioMetrics: "audio-metrics",
387
+ automationControl: "automation-control",
388
+ battery: "battery",
389
+ binary: "binary",
390
+ brightness: "brightness",
391
+ cameraStreams: "camera-streams",
392
+ carbonMonoxide: "carbon-monoxide",
393
+ climateControl: "climate-control",
394
+ color: "color",
395
+ connectivity: "connectivity",
396
+ consumables: "consumables",
397
+ contact: "contact",
398
+ control: "control",
399
+ cover: "cover",
400
+ dayNight: "day-night",
401
+ deviceStatus: "device-status",
402
+ dishwasher: "dishwasher",
403
+ doNotDisturb: "do-not-disturb",
404
+ doorbell: "doorbell",
405
+ energySystem: "energy-system",
406
+ enumSensor: "enum-sensor",
407
+ error: "error",
408
+ eventEmitter: "event-emitter",
409
+ fanControl: "fan-control",
410
+ featureProbe: "feature-probe",
411
+ flood: "flood",
412
+ gas: "gas",
413
+ groupActive: "group-active",
414
+ groupCommands: "group-commands",
415
+ groupStatus: "group-status",
416
+ heatingValve: "heating-valve",
417
+ heatPumpStatus: "heat-pump-status",
418
+ humidifier: "humidifier",
419
+ humiditySensor: "humidity-sensor",
420
+ image: "image",
421
+ imageSettings: "image-settings",
422
+ intercom: "intercom",
423
+ irTransmitter: "ir-transmitter",
424
+ lawnMowerControl: "lawn-mower-control",
425
+ lockControl: "lock-control",
426
+ lowPowerSleep: "low-power-sleep",
427
+ mediaPlayer: "media-player",
428
+ meter: "meter",
429
+ motion: "motion",
430
+ motionTrigger: "motion-trigger",
431
+ motionZones: "motion-zones",
432
+ nativeObjectDetection: "native-object-detection",
433
+ navigation: "navigation",
434
+ networkLink: "network-link",
435
+ notifier: "notifier",
436
+ numericSensor: "numeric-sensor",
437
+ petFeeder: "pet-feeder",
438
+ petFountain: "pet-fountain",
439
+ powerMeter: "power-meter",
440
+ powerSource: "power-source",
441
+ presence: "presence",
442
+ pressureSensor: "pressure-sensor",
443
+ privacyMask: "privacy-mask",
444
+ ptzAutotrack: "ptz-autotrack",
445
+ pumpCycle: "pump-cycle",
446
+ recordingOnboard: "recording-onboard",
447
+ recordingSignal: "recording-signal",
448
+ runningState: "running-state",
449
+ sceneMonitor: "scene-monitor",
450
+ scriptRunner: "script-runner",
451
+ siren: "siren",
452
+ smoke: "smoke",
453
+ streamCatalog: "stream-catalog",
454
+ streamParams: "stream-params",
455
+ streamSignals: "stream-signals",
456
+ switch: "switch",
457
+ tamper: "tamper",
458
+ temperatureSensor: "temperature-sensor",
459
+ timedRun: "timed-run",
460
+ update: "update",
461
+ vacuumControl: "vacuum-control",
462
+ valve: "valve",
463
+ vibration: "vibration",
464
+ waterHeater: "water-heater",
465
+ weather: "weather",
466
+ weatherStation: "weather-station",
467
+ workload: "workload",
468
+ zoneAnalytics: "zone-analytics",
469
+ zoneRules: "zone-rules",
470
+ zones: "zones"
471
+ };
472
+ //#endregion
473
+ //#region ../types/dist/esm/device/base-device.mjs
474
+ var BaseDevice = class {
475
+ id;
476
+ stableId;
477
+ type;
478
+ /** True when another process owns the base slices (`options.deviceStatus: 'external'`). */
479
+ statusIsExternal;
480
+ /** The fault catalog the integration declared; `[]` until it does. */
481
+ faultTypes = [];
482
+ name;
483
+ parentDeviceId;
484
+ role;
485
+ /**
486
+ * Cap-keyed runtime-state slice is the single source of truth for
487
+ * `online`. Both getter and setter proxy to the slice — drivers can
488
+ * write `this.online = true` ergonomically, and the cap event fires
489
+ * automatically through the runtime-state writer. `markOnline()` is
490
+ * kept as the explicit method form mandated by `IDevice`.
491
+ */
492
+ get online() {
493
+ return this.runtimeState.getCapState("device-status")?.online ?? false;
494
+ }
495
+ set online(value) {
496
+ this.markOnline(value);
497
+ }
498
+ /**
499
+ * Generic per-cap runtime-state namespace. One entry per cap with
500
+ * `runtimeState:` declared, auto-generated by codegen — see
501
+ * `device-local-state.ts`. Drivers access via:
502
+ *
503
+ * `this.state.battery.sleeping = true` // patches the battery slice
504
+ * `const pct = this.state.battery.level` // reads the battery slice
505
+ * `this.state.deviceStatus.online = true` // mirrors `markOnline(true)`
506
+ *
507
+ * Adding a new cap with `runtimeState:` automatically extends this
508
+ * namespace — drivers don't have to declare proxies. Reads return
509
+ * `undefined` when the slice hasn't been seeded; writes patch via
510
+ * `runtimeState.patchCapState` and validate against the cap's schema
511
+ * (so partial writes need the slice to be seeded with the required
512
+ * fields first — drivers do this on cap registration).
513
+ *
514
+ * For caps not exposed in `DeviceLocalState`, drivers can build their
515
+ * own typed proxy via `this.sliceProxy(cap)`.
516
+ */
517
+ get state() {
518
+ if (!this._stateProxyCache) {
519
+ const cache = {};
520
+ const handler = { get: (target, key) => {
521
+ const k = key;
522
+ const existing = Reflect.get(target, k);
523
+ if (existing !== void 0) return existing;
524
+ const capName = DEVICE_LOCAL_STATE_CAP_NAMES[k];
525
+ if (!capName) return void 0;
526
+ const proxy = this.sliceProxyByName(capName);
527
+ Reflect.set(target, k, proxy);
528
+ return proxy;
529
+ } };
530
+ this._stateProxyCache = new Proxy(cache, handler);
531
+ }
532
+ return this._stateProxyCache;
533
+ }
534
+ _stateProxyCache;
535
+ config;
536
+ /**
537
+ * Per-device runtime state, cap-keyed. Always installed — slices
538
+ * for individual caps materialise as those caps register their
539
+ * native providers (`ctx.registerNativeCap`). The cap's own
540
+ * `runtimeState` schema is the source of truth for the slice
541
+ * shape; drivers don't redeclare it, they just write through.
542
+ *
543
+ * Read: `this.runtimeState.getCapState('battery')` →
544
+ * `{level, charging, sleeping, lastUpdated}` for any
545
+ * provider that registers `batteryCapability`.
546
+ * Write: `this.runtimeState.setCapState('battery', { … })`.
547
+ *
548
+ * Cross-process consumers reach this state through the
549
+ * `deviceState` cap router (or via cap-specific events the driver
550
+ * emits — e.g. `battery.onStatusChanged`). The local handle is
551
+ * accessed in-process by the driver to avoid roundtrips.
552
+ */
553
+ runtimeState;
554
+ ctx;
555
+ /**
556
+ * Operator-organisational location label (room / area / zone).
557
+ * Read from `ctx.deviceMeta.location`; mutated via
558
+ * `kernel.devices.setLocation(id, value)`. Free-text — providers
559
+ * don't interpret it; the UI groups devices by this for filters
560
+ * like "show me all cameras in Kitchen". `null` when unset.
561
+ */
562
+ location;
563
+ /**
564
+ * Soft-disabled flag. When `true`, the device class is still
565
+ * instantiated and visible in the UI (so the operator can flip
566
+ * back on without re-adding) but lifecycle hooks (publishToBroker,
567
+ * alarm-stream subscribe, …) MUST be gated by the driver to skip
568
+ * work. The `BaseDevice` enforces this by exposing the flag here;
569
+ * it does NOT mutate cap behaviour automatically — drivers consult
570
+ * `this.disabled` at the top of their lifecycle methods. Read from
571
+ * `ctx.deviceMeta.disabled`; mutated via
572
+ * `kernel.devices.setDisabled(id, value)`.
573
+ */
574
+ disabled;
575
+ /**
576
+ * Cached materialised `SourceInfo` — either the value persisted under
577
+ * `metadata.sourceInfo` at construction time, or a synthetic
578
+ * `{ id: stableId, system: addonId }` for providers that haven't
579
+ * migrated yet. Lazily populated on first `sourceInfo` read so the
580
+ * cost of Zod-parsing the meta blob is paid once per device boot.
581
+ * Invalidated by `updateSourceInfo()` so providers see the new value
582
+ * back through the getter without a re-fetch from the meta surface.
583
+ */
584
+ _sourceInfoCache = null;
585
+ constructor(ctx, schema, options) {
586
+ this.ctx = ctx;
587
+ this.id = ctx.id;
588
+ this.stableId = ctx.stableId;
589
+ this.type = options.type;
590
+ if (!ctx.deviceMeta) throw new Error(`BaseDevice constructor: ctx.deviceMeta is required (id=${ctx.id} stableId=${ctx.stableId})`);
591
+ this.name = ctx.deviceMeta.name;
592
+ this.location = ctx.deviceMeta.location;
593
+ this.disabled = ctx.deviceMeta.disabled;
594
+ this.role = options.role;
595
+ this.parentDeviceId = ctx.parentDeviceId;
596
+ const seedData = ctx.persistedConfig ?? {};
597
+ const declaredSecretPaths = collectZodSecretPaths(schema);
598
+ this.config = DeviceConfig.fromSchema(schema, (data) => ctx.persistConfig(data, { secretConfigPaths: declaredSecretPaths }), seedData, ({ droppedKeys, issues }) => {
599
+ ctx.logger.warn("Device config recovery: dropping invalid persisted fields", {
600
+ tags: {
601
+ deviceId: ctx.id,
602
+ stableId: ctx.stableId
603
+ },
604
+ meta: {
605
+ droppedKeys: [...droppedKeys],
606
+ firstIssue: issues[0]?.message ?? null
607
+ }
608
+ });
609
+ });
610
+ let cachedProxy = null;
611
+ const writer = async (capName, slice) => {
612
+ if (!cachedProxy) cachedProxy = ctx.fetchDevice(ctx.id);
613
+ await (await cachedProxy).deviceState.setCapSlice({
614
+ capName,
615
+ slice
616
+ });
617
+ };
618
+ const initial = ctx.initialRuntimeState ?? {};
619
+ const onWriteFailed = (cap, error) => {
620
+ ctx.logger.warn("runtime-state write refused by the hub — the slice is not mirrored; it is re-sent on the next write", {
621
+ tags: { deviceId: ctx.id },
622
+ meta: {
623
+ cap,
624
+ error
625
+ }
626
+ });
627
+ };
628
+ this.runtimeState = DeviceRuntimeState.fromInitial(initial, writer, onWriteFailed);
629
+ ctx.bindRuntimeState?.(this.runtimeState);
630
+ this.statusIsExternal = options.deviceStatus === "external";
631
+ if (!this.statusIsExternal) ctx.registerNativeCap?.(deviceStatusCapability, {});
632
+ if (!this.statusIsExternal) {
633
+ const seed = {
634
+ online: true,
635
+ lastChangedAt: Date.now()
636
+ };
637
+ this.runtimeState.setCapState("device-status", seed);
638
+ }
639
+ if (!this.statusIsExternal) {
640
+ ctx.registerNativeCap?.(featureProbeCapability, {});
641
+ this.runtimeState.setCapState("feature-probe", {
642
+ flags: {},
643
+ deviceType: null,
644
+ model: null,
645
+ channelCount: null,
646
+ lastProbedAt: 0,
647
+ lastFetchedAt: 0
648
+ });
649
+ }
650
+ }
651
+ deviceActions = /* @__PURE__ */ new Map();
652
+ /** Declare a device custom action + its typed handler. Idempotent per name. */
653
+ registerDeviceAction(name, spec, handler) {
654
+ this.deviceActions.set(name, {
655
+ spec,
656
+ handler
657
+ });
658
+ }
659
+ /** Invoke a registered device action. Validates input against the spec. */
660
+ async runDeviceAction(action, input) {
661
+ const entry = this.deviceActions.get(action);
662
+ if (!entry) throw new Error(`unknown device action "${action}" on device ${this.id}`);
663
+ const parsed = entry.spec.input.parse(input);
664
+ return entry.handler(parsed);
665
+ }
666
+ async removeDevice() {}
667
+ /**
668
+ * Set the device's online flag. Called by `BaseDeviceProvider` after
669
+ * aggregating per-profile stream-broker health, or directly by drivers
670
+ * that have provider-side liveness signals (e.g. ONVIF heartbeats,
671
+ * Reolink Baichuan firmware push events). Mirrors the new value into
672
+ * the `device-status` runtime-state slice so cross-process consumers
673
+ * pick it up via the standard cap-state channel. Subclasses can
674
+ * override to gate side effects on the transition.
675
+ */
676
+ markOnline(online) {
677
+ if (this.statusIsExternal || this.online === online) return;
678
+ const next = {
679
+ online,
680
+ lastChangedAt: Date.now()
681
+ };
682
+ this.runtimeState.setCapState("device-status", next);
683
+ }
684
+ /**
685
+ * Upstream-system identity + rendering envelope for this device. See
686
+ * `SourceInfo` for the field contract. Always returns a valid object:
687
+ * if the persisted `metadata.sourceInfo` blob is absent or fails Zod
688
+ * validation, falls back to a synthetic `{ id: stableId, system: addonId }`
689
+ * so providers that haven't migrated keep working without code changes.
690
+ *
691
+ * The value is cached after the first read. `updateSourceInfo()`
692
+ * invalidates the cache so subsequent reads see the new patch. The
693
+ * returned object is frozen to prevent accidental in-place mutation —
694
+ * use `updateSourceInfo({ patch })` to change fields.
695
+ */
696
+ get sourceInfo() {
697
+ if (this._sourceInfoCache) return this._sourceInfoCache;
698
+ const resolved = extractSourceInfoFromMetadata(this.ctx.deviceMeta.metadata) ?? synthesizeSourceInfo({
699
+ stableId: this.stableId,
700
+ addonId: this.ctx.deviceMeta.addonId
701
+ });
702
+ this._sourceInfoCache = Object.freeze({ ...resolved });
703
+ return this._sourceInfoCache;
704
+ }
705
+ /**
706
+ * Convenience accessor for the upstream dispatch key. Equivalent to
707
+ * `this.sourceInfo.id` — providers use this to keep a
708
+ * `Map<sourceId, IDevice>` for routing inbound push events.
709
+ */
710
+ get sourceId() {
711
+ return this.sourceInfo.id;
712
+ }
713
+ /**
714
+ * Patch the device's `SourceInfo`. Shallow-merges `patch` over the
715
+ * current value, persists the merged result under
716
+ * `metadata.sourceInfo` via the `device-manager.setMetadata` cap, and
717
+ * emits `EventCategory.DeviceSourceInfoChanged` for live consumers.
718
+ *
719
+ * Safe to call from anywhere in the device's lifetime — the call is
720
+ * idempotent for `undefined` patch values (ignored) and best-effort
721
+ * for persistence (a transient device-manager error doesn't unwind
722
+ * the local cache update, so subsequent reads still see the patch).
723
+ *
724
+ * Drivers populate this on adoption + on every metadata change push
725
+ * from the upstream source. Subscribers (UI, export adapters) react
726
+ * via the `DeviceSourceInfoChanged` event without polling.
727
+ */
728
+ async updateSourceInfo(patch) {
729
+ const next = mergeSourceInfo(this.sourceInfo, patch);
730
+ this._sourceInfoCache = Object.freeze({ ...next });
731
+ const action = this.ctx.api.deviceManager?.setMetadata;
732
+ if (action) try {
733
+ await action.mutate({
734
+ deviceId: this.id,
735
+ patch: { [SOURCE_INFO_METADATA_KEY]: next }
736
+ });
737
+ } catch {}
738
+ this.ctx.eventBus.emit(createEvent("device.source-info-changed", {
739
+ type: "device",
740
+ id: this.stableId
741
+ }, {
742
+ deviceId: this.id,
743
+ sourceInfo: next
744
+ }));
745
+ }
746
+ /**
747
+ * Declare this device's identifiers (D1059): MAC(s), serial, vendor uid,
748
+ * machine uuid, hostname, IP — what a later step matches across integrations.
749
+ * Normalises `raw` (`normaliseIdentifiers`), logs every refused value, and
750
+ * writes the result through `device-manager.setIdentifiers`, which accepts it
751
+ * only from the provider that owns this device. Each kind it carries replaces
752
+ * the stored one and each kind it lacks is removed — except the kinds listed in
753
+ * `options.unread` (reads that FAILED), which keep their stored value. Pass
754
+ * everything read in one call; a call where every kind is unread writes
755
+ * nothing. Best-effort: never throws.
756
+ */
757
+ async declareIdentifiers(raw, options) {
758
+ return declareDeviceIdentifiers({
759
+ deviceId: this.id,
760
+ logger: this.ctx.logger,
761
+ writer: this.ctx.api.deviceManager?.setIdentifiers
762
+ }, raw, options);
763
+ }
764
+ /**
765
+ * Declare the identity of the device at the FAR END of this device's physical
766
+ * link (D1063): a PoE port's wired client. Same normalisation, `unread`
767
+ * rule and owner check as {@link declareIdentifiers}, written through
768
+ * `device-manager.setAttachedIdentifiers`. It never makes the two devices the
769
+ * same device. Best-effort: never throws.
770
+ */
771
+ async declareAttachedIdentifiers(raw, options) {
772
+ return declareDeviceIdentifiers({
773
+ deviceId: this.id,
774
+ logger: this.ctx.logger,
775
+ writer: this.ctx.api.deviceManager?.setAttachedIdentifiers
776
+ }, raw, options);
777
+ }
778
+ /**
779
+ * Re-publish the device's current `features` array to the persisted
780
+ * meta blob. Drivers call this after a probe finishes when the live
781
+ * `features` getter has gained new flags (e.g. `hasIntercom` flips
782
+ * to true → `DeviceFeature.TwoWayAudio` joins the list).
783
+ *
784
+ * Without this, only the construction-time snapshot is written —
785
+ * `deviceManager.registerDevice` is invoked once per boot, so probe-
786
+ * driven additions don't reach the persisted index until the next
787
+ * server restart, and `getDevice` / `listAll` keep returning the
788
+ * stale list for forked-worker devices (whose live IDevice instance
789
+ * is invisible to the hub registry).
790
+ *
791
+ * Idempotent: re-calling with the same features just no-ops on the
792
+ * persisted meta. Best-effort: lookup or write failures are logged
793
+ * at debug and swallowed — the live `device.features` getter is
794
+ * still authoritative within this process, so callers never block
795
+ * device boot on a meta refresh.
796
+ */
797
+ async refreshFeatures() {
798
+ const action = this.ctx.api.deviceManager?.registerDevice;
799
+ if (!action) return;
800
+ try {
801
+ await action.mutate({
802
+ addonId: this.ctx.deviceMeta.addonId,
803
+ stableId: this.stableId,
804
+ id: this.id,
805
+ type: this.type,
806
+ name: this.name,
807
+ parentDeviceId: this.parentDeviceId,
808
+ features: [...this.features],
809
+ config: {}
810
+ });
811
+ } catch (err) {}
812
+ }
813
+ /**
814
+ * Declare that this device can report a fault (the `error` cap). The slice
815
+ * starts UNKNOWN — a restored slice is kept, so a fault that was open before
816
+ * a restart is compared, not announced again.
817
+ */
818
+ registerErrorCap() {
819
+ this.ctx.registerNativeCap?.(errorCapability, { listFaultTypes: async () => ({ types: [...this.faultTypes] }) });
820
+ if (this.runtimeState.getCapState(errorCapability.name) === void 0) this.setCapSlice(errorCapability, ERROR_STATUS_COLD);
821
+ }
822
+ /**
823
+ * Declare the fault kinds this device's integration can raise (code, label,
824
+ * severity), served by `error.listFaultTypes` so a rule's code picker is
825
+ * offered the integration's own words. The default is `[]`; a fault outside
826
+ * the catalog is still published. Call it before or after `registerErrorCap`.
827
+ */
828
+ declareFaultTypes(types) {
829
+ this.faultTypes = types.map((type) => ({ ...type }));
830
+ }
831
+ /**
832
+ * Publish the device's fault. The slice is written; on an EDGE (a fault
833
+ * starts, or one resolves) an attention episode opens or closes through the
834
+ * alerts cap, which the notification center announces as
835
+ * `device-attention-required` / `-resolved`. An unknown reading is never an
836
+ * edge. No rule exists by default: it notifies when the operator makes one.
837
+ */
838
+ async publishError(reading) {
839
+ const previous = this.getCapSlice(errorCapability);
840
+ if (reading.active === null && previous !== null && previous.active !== null) return;
841
+ const now = Date.now();
842
+ const edge = deviceErrorEdge(previous, reading);
843
+ const next = edge === "start" && reading.since === null ? {
844
+ ...reading,
845
+ since: now
846
+ } : reading;
847
+ this.setCapSlice(errorCapability, next);
848
+ if (edge === null) return;
849
+ const alerts = this.ctx.api.alerts;
850
+ if (alerts === void 0) {
851
+ this.ctx.logger.warn("device error: attention event skipped — alerts capability missing", {
852
+ tags: { deviceId: this.id },
853
+ meta: { edge }
854
+ });
855
+ return;
856
+ }
857
+ try {
858
+ if (edge === "start") await alerts.emit.mutate(buildDeviceErrorAlert(this.id, this.name, next, now));
859
+ else await alerts.update.mutate({
860
+ alertId: deviceErrorAlertId(this.id),
861
+ patch: {
862
+ status: "completed",
863
+ read: true,
864
+ updatedAt: now
865
+ }
866
+ });
867
+ this.ctx.logger.info(`device error: ${edge === "start" ? "raised" : "resolved"}`, {
868
+ tags: { deviceId: this.id },
869
+ meta: {
870
+ code: next.code,
871
+ label: next.label
872
+ }
873
+ });
874
+ } catch (err) {
875
+ this.ctx.logger.warn("device error: attention event failed", {
876
+ tags: { deviceId: this.id },
877
+ meta: {
878
+ edge,
879
+ error: errMsg(err)
880
+ }
881
+ });
882
+ }
883
+ }
884
+ /**
885
+ * Typed read-through to a cap-keyed runtime-state slice. Drivers
886
+ * call `this.getCapSlice(batteryCapability)` and the return type
887
+ * is inferred from the cap's `runtimeState` Zod schema — no string
888
+ * key, no manual generic. Returns `null` when the slice hasn't
889
+ * been written yet (e.g. driver hasn't seeded battery yet).
890
+ */
891
+ getCapSlice(cap) {
892
+ return this.runtimeState.getCapState(cap.name) ?? null;
893
+ }
894
+ /**
895
+ * Typed writer to a cap-keyed runtime-state slice. Routes through
896
+ * the runtime-state writer (validate → persist → emit cap event).
897
+ * Equivalent to `this.runtimeState.setCapState(cap.name, value)`
898
+ * but with the cap's `runtimeState` schema enforcing the value
899
+ * shape at compile time. Mirrors the symmetry of
900
+ * `getCapSlice` / `setCapSlice` for cross-cap consistency.
901
+ */
902
+ setCapSlice(cap, value) {
903
+ this.runtimeState.setCapState(cap.name, value);
904
+ }
905
+ /**
906
+ * Field-level read/write proxy over a cap's runtime-state slice.
907
+ * Drivers that want ergonomic per-field access declare:
908
+ *
909
+ * ```ts
910
+ * protected battery = this.sliceProxy(batteryCapability)
911
+ * // …
912
+ * this.battery.sleeping = true // patches the slice
913
+ * const charging = this.battery.charging // reads the slice
914
+ * ```
915
+ *
916
+ * Reads return `undefined` when the slice hasn't been seeded yet
917
+ * (cap not registered, or seeded but the field is absent). Writes
918
+ * route through `runtimeState.patchCapState` so the cap's `runtimeState`
919
+ * schema validates the merged result and the cap event fires.
920
+ *
921
+ * Pattern is generic — same shape works for `battery`, `device-status`,
922
+ * `motion`, `doorbell`, anything with a `runtimeState:` schema. Drivers
923
+ * declare one proxy per cap they read/write directly.
924
+ */
925
+ sliceProxy(cap) {
926
+ return this.sliceProxyByName(cap.name);
927
+ }
928
+ /**
929
+ * The same proxy built from a cap NAME: the proxy reads nothing else of the
930
+ * definition, and `this.state` has only names (a definition would put every
931
+ * device-native schema in the bundle of every device provider).
932
+ */
933
+ sliceProxyByName(capName) {
934
+ return new Proxy({}, {
935
+ get: (_, key) => {
936
+ return this.runtimeState.getCapState(capName)?.[key];
937
+ },
938
+ set: (_, key, value) => {
939
+ this.runtimeState.patchCapState(capName, { [key]: value });
940
+ return true;
941
+ },
942
+ has: (_, key) => {
943
+ const slice = this.runtimeState.getCapState(capName);
944
+ return slice ? key in slice : false;
945
+ },
946
+ ownKeys: () => {
947
+ const slice = this.runtimeState.getCapState(capName);
948
+ return slice ? Object.keys(slice) : [];
949
+ },
950
+ getOwnPropertyDescriptor: (_, key) => {
951
+ const slice = this.runtimeState.getCapState(capName);
952
+ if (!slice || !(key in slice)) return void 0;
953
+ return {
954
+ configurable: true,
955
+ enumerable: true,
956
+ value: slice[key]
957
+ };
958
+ }
959
+ });
960
+ }
961
+ /**
962
+ * Default empty settings UI. Drivers override this to expose an
963
+ * editable form in the device-details page. Returning an empty sections
964
+ * array signals "nothing to contribute" — the aggregator drops the
965
+ * contribution entirely rather than rendering a blank panel.
966
+ */
967
+ getSettingsUISchema() {
968
+ return { sections: [] };
969
+ }
970
+ /**
971
+ * Default write path: forward the flat patch directly to storage.
972
+ * Drivers that project a UI shape different from storage (e.g. `RtspCamera`
973
+ * exposing `mainStreamUrl`/`subStreamUrl` over `streams[]`) override this
974
+ * to reshape before `config.setAll`.
975
+ */
976
+ async applySettingsPatch(patch) {
977
+ await this.config.setAll(patch);
978
+ }
979
+ /**
980
+ * Phase 3 — populate device-scoped state needed by downstream phases
981
+ * (accessory reconciliation, public `features` array, optional cap
982
+ * registration). Called ONCE per construction, after register but
983
+ * before `getAccessoryChildren()`.
984
+ *
985
+ * Drivers write the `feature-probe` runtime-state slice via
986
+ * `this.runtimeState.setCapState('feature-probe', {...})` — flag bag
987
+ * is open (Reolink writes `hasPtz/hasIntercom`, Hikvision writes
988
+ * `hasSupplementalLight/hasAlarmIo`, etc).
989
+ *
990
+ * Default: nothing to probe → mark the device PROBED (set `lastProbedAt`) so
991
+ * the kernel treats it as ready immediately. A device that derives its shape
992
+ * from a spec (a container, or an accessory sensor) rather than from a
993
+ * hardware probe has no probe to "complete"; without stamping `lastProbedAt`
994
+ * it would look perpetually un-probed — logging "Initial probe did not
995
+ * complete" on every boot and spinning a pointless retry chain. Drivers that
996
+ * DO probe override this and write their own `feature-probe` slice (including
997
+ * `lastProbedAt`) once their probe actually succeeds.
998
+ */
999
+ async onProbe() {
1000
+ if (this.statusIsExternal) return;
1001
+ const base = this.runtimeState.getCapState("feature-probe") ?? {
1002
+ flags: {},
1003
+ deviceType: null,
1004
+ model: null,
1005
+ channelCount: null,
1006
+ lastProbedAt: 0,
1007
+ lastFetchedAt: 0
1008
+ };
1009
+ this.runtimeState.setCapState("feature-probe", {
1010
+ ...base,
1011
+ lastProbedAt: Date.now()
1012
+ });
1013
+ }
1014
+ /**
1015
+ * Phase 5 — fired after the device + its accessories are registered.
1016
+ * Drivers publish streams to the broker, kick off background tasks,
1017
+ * or subscribe to lib events that need a fully-registered device id.
1018
+ *
1019
+ * Default: no-op.
1020
+ *
1021
+ * RENAMED FROM `onCreated` (which still exists for back-compat in this
1022
+ * pass). The new name reflects the post-probe, post-accessory contract.
1023
+ */
1024
+ async onActivate() {}
1025
+ /**
1026
+ * Re-run the probe + reconcile accessories + refresh features meta.
1027
+ * Drivers call this when device-side state changes (battery cam wakes,
1028
+ * firmware update, manual operator trigger).
1029
+ *
1030
+ * The kernel injects `_kernelReprobe` on registration so this method
1031
+ * delegates to the same orchestrator that runs the boot-time phase
1032
+ * 3 + 4 sequence. Drivers should NOT override this — they override
1033
+ * `onProbe()` instead.
1034
+ */
1035
+ async reprobe() {
1036
+ if (this._kernelReprobe) await this._kernelReprobe();
1037
+ else await this.onProbe();
1038
+ }
1039
+ /**
1040
+ * Kernel-injected callback that runs the full post-probe orchestration
1041
+ * (onProbe → registerDevice meta refresh → accessory reconciliation).
1042
+ * Set by `device-cap-proxy.register()`. Drivers should not touch this
1043
+ * directly — call `reprobe()` instead.
1044
+ */
1045
+ _kernelReprobe;
1046
+ /**
1047
+ * Declare accessory child devices the kernel should auto-spawn
1048
+ * after `onProbe()` resolves. Each spec fully describes one child
1049
+ * — stableId suffix (deterministic per kind for restore-safety),
1050
+ * meta (type / name / location), config (initial blob the child
1051
+ * self-hydrates), and a factory that constructs the concrete
1052
+ * class with whatever closure-captured refs it needs (typically
1053
+ * `this` for the parent reference).
1054
+ *
1055
+ * The kernel handles the rest: allocateDeviceId, persistInitialConfig
1056
+ * (skipped on restore when the row already exists),
1057
+ * persistInitialMeta, createContext, factory invocation, register,
1058
+ * and recursive lifecycle (probe + accessories + activate).
1059
+ *
1060
+ * Implementations should derive children from
1061
+ * `this.runtimeState.getCapState('feature-probe')` (post-probe truth).
1062
+ * Drivers can use the `getProbeFlags()` helper to read the flag bag
1063
+ * with a typed cast.
1064
+ *
1065
+ * Answer what you KNOW. A plain array is read as the complete list only
1066
+ * while this device is `online` and probed; return
1067
+ * `accessoryChildrenUnknown(reason)` whenever you cannot know the list right
1068
+ * now (no credentials, parent not connected, a failed or partial read) —
1069
+ * the kernel then deletes nothing. Return `accessoryChildrenComplete(list)`
1070
+ * to say "connected, and this is the complete list" explicitly. A shrink is
1071
+ * deleted only after a second agreeing complete read on a later probe (D49;
1072
+ * `packages/system/src/kernel/moleculer/accessory-prune-gate.ts`).
1073
+ *
1074
+ * Default: no children.
1075
+ */
1076
+ getAccessoryChildren() {
1077
+ return [];
1078
+ }
1079
+ /**
1080
+ * Read the current feature-probe flag bag with a typed cast. Helper
1081
+ * for `getAccessoryChildren()` and `features` getters that derive
1082
+ * outputs from the probe results.
1083
+ */
1084
+ getProbeFlags() {
1085
+ return this.runtimeState.getCapState("feature-probe")?.flags ?? {};
1086
+ }
1087
+ /**
1088
+ * Returns true once `onProbe` has completed at least once
1089
+ * (`lastProbedAt > 0`). Drivers gate `getAccessoryChildren()` on this
1090
+ * to avoid spawning stale accessories on a fresh device whose probe
1091
+ * hasn't landed yet.
1092
+ */
1093
+ hasProbed() {
1094
+ return (this.runtimeState.getCapState("feature-probe")?.lastProbedAt ?? 0) > 0;
1095
+ }
1096
+ };
1097
+ //#endregion
1098
+ export { BaseDevice as t };