@camstack/core 0.1.15 → 0.1.16

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 (382) hide show
  1. package/dist/addon/addon-api-factory.d.ts +36 -0
  2. package/dist/addon/addon-api-factory.d.ts.map +1 -0
  3. package/dist/addon-routes/addon-route-registry.d.ts +38 -0
  4. package/dist/addon-routes/addon-route-registry.d.ts.map +1 -0
  5. package/dist/auth/api-key-manager.d.ts +27 -0
  6. package/dist/auth/api-key-manager.d.ts.map +1 -0
  7. package/dist/auth/auth-manager.d.ts +47 -0
  8. package/dist/auth/auth-manager.d.ts.map +1 -0
  9. package/dist/auth/parse-record.d.ts +19 -0
  10. package/dist/auth/parse-record.d.ts.map +1 -0
  11. package/dist/auth/scoped-token-manager.d.ts +18 -0
  12. package/dist/auth/scoped-token-manager.d.ts.map +1 -0
  13. package/dist/auth/user-manager.d.ts +34 -0
  14. package/dist/auth/user-manager.d.ts.map +1 -0
  15. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.d.ts +54 -0
  16. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.d.ts.map +1 -0
  17. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +223 -217
  18. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js.map +1 -1
  19. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +216 -7
  20. package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs.map +1 -1
  21. package/dist/builtins/addon-pages-aggregator/index.d.ts +2 -0
  22. package/dist/builtins/addon-pages-aggregator/index.d.ts.map +1 -0
  23. package/dist/builtins/addon-pages-aggregator/index.js +6 -221
  24. package/dist/builtins/addon-pages-aggregator/index.mjs +2 -9
  25. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts +33 -0
  26. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.d.ts.map +1 -0
  27. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +199 -197
  28. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js.map +1 -1
  29. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +192 -7
  30. package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs.map +1 -1
  31. package/dist/builtins/addon-widgets-aggregator/index.d.ts +2 -0
  32. package/dist/builtins/addon-widgets-aggregator/index.d.ts.map +1 -0
  33. package/dist/builtins/addon-widgets-aggregator/index.js +6 -201
  34. package/dist/builtins/addon-widgets-aggregator/index.mjs +2 -9
  35. package/dist/builtins/alerts/alerts.addon.d.ts +82 -0
  36. package/dist/builtins/alerts/alerts.addon.d.ts.map +1 -0
  37. package/dist/builtins/alerts/alerts.addon.js +590 -430
  38. package/dist/builtins/alerts/alerts.addon.js.map +1 -1
  39. package/dist/builtins/alerts/alerts.addon.mjs +595 -7
  40. package/dist/builtins/alerts/alerts.addon.mjs.map +1 -1
  41. package/dist/builtins/alerts/index.d.ts +2 -0
  42. package/dist/builtins/alerts/index.d.ts.map +1 -0
  43. package/dist/builtins/alerts/index.js +3 -443
  44. package/dist/builtins/alerts/index.mjs +2 -8
  45. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.d.ts +8 -0
  46. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.d.ts.map +1 -0
  47. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.js +56 -0
  48. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.js.map +1 -0
  49. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.mjs +50 -0
  50. package/dist/builtins/auth-orchestrator/auth-orchestrator.addon.mjs.map +1 -0
  51. package/dist/builtins/auth-orchestrator/index.d.ts +2 -0
  52. package/dist/builtins/auth-orchestrator/index.d.ts.map +1 -0
  53. package/dist/builtins/auth-orchestrator/index.js +7 -0
  54. package/dist/builtins/auth-orchestrator/index.mjs +2 -0
  55. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.d.ts +148 -0
  56. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.d.ts.map +1 -0
  57. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +7639 -0
  58. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js.map +1 -0
  59. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +7627 -0
  60. package/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs.map +1 -0
  61. package/dist/builtins/backup-orchestrator/cron-helpers.d.ts +24 -0
  62. package/dist/builtins/backup-orchestrator/cron-helpers.d.ts.map +1 -0
  63. package/dist/builtins/backup-orchestrator/destination-policy.d.ts +73 -0
  64. package/dist/builtins/backup-orchestrator/destination-policy.d.ts.map +1 -0
  65. package/dist/builtins/backup-orchestrator/download-helpers.d.ts +13 -0
  66. package/dist/builtins/backup-orchestrator/download-helpers.d.ts.map +1 -0
  67. package/dist/builtins/backup-orchestrator/index.d.ts +3 -0
  68. package/dist/builtins/backup-orchestrator/index.d.ts.map +1 -0
  69. package/dist/builtins/backup-orchestrator/index.js +7 -0
  70. package/dist/builtins/backup-orchestrator/index.mjs +2 -0
  71. package/dist/builtins/backup-orchestrator/manifest-store.d.ts +78 -0
  72. package/dist/builtins/backup-orchestrator/manifest-store.d.ts.map +1 -0
  73. package/dist/builtins/console-logging/console-destination.d.ts +14 -0
  74. package/dist/builtins/console-logging/console-destination.d.ts.map +1 -0
  75. package/dist/builtins/console-logging/console-logging.addon.d.ts +26 -0
  76. package/dist/builtins/console-logging/console-logging.addon.d.ts.map +1 -0
  77. package/dist/builtins/console-logging/index.d.ts +4 -0
  78. package/dist/builtins/console-logging/index.d.ts.map +1 -0
  79. package/dist/builtins/console-logging/index.js +99 -235
  80. package/dist/builtins/console-logging/index.js.map +1 -1
  81. package/dist/builtins/console-logging/index.mjs +95 -9
  82. package/dist/builtins/console-logging/index.mjs.map +1 -1
  83. package/dist/builtins/device-manager/device-event-propagator.d.ts +27 -0
  84. package/dist/builtins/device-manager/device-event-propagator.d.ts.map +1 -0
  85. package/dist/builtins/device-manager/device-manager.addon.d.ts +259 -0
  86. package/dist/builtins/device-manager/device-manager.addon.d.ts.map +1 -0
  87. package/dist/builtins/device-manager/device-manager.addon.js +2125 -2127
  88. package/dist/builtins/device-manager/device-manager.addon.js.map +1 -1
  89. package/dist/builtins/device-manager/device-manager.addon.mjs +2145 -7
  90. package/dist/builtins/device-manager/device-manager.addon.mjs.map +1 -1
  91. package/dist/builtins/device-manager/index.d.ts +3 -0
  92. package/dist/builtins/device-manager/index.d.ts.map +1 -0
  93. package/dist/builtins/device-manager/index.js +6 -2156
  94. package/dist/builtins/device-manager/index.mjs +2 -10
  95. package/dist/builtins/hub-forwarder/hub-forwarder-destination.d.ts +45 -0
  96. package/dist/builtins/hub-forwarder/hub-forwarder-destination.d.ts.map +1 -0
  97. package/dist/builtins/hub-forwarder/hub-forwarder.addon.d.ts +16 -0
  98. package/dist/builtins/hub-forwarder/hub-forwarder.addon.d.ts.map +1 -0
  99. package/dist/builtins/hub-forwarder/index.d.ts +4 -0
  100. package/dist/builtins/hub-forwarder/index.d.ts.map +1 -0
  101. package/dist/builtins/hub-forwarder/index.js +150 -291
  102. package/dist/builtins/hub-forwarder/index.js.map +1 -1
  103. package/dist/builtins/hub-forwarder/index.mjs +145 -9
  104. package/dist/builtins/hub-forwarder/index.mjs.map +1 -1
  105. package/dist/builtins/local-auth/auth-schema.d.ts +12 -0
  106. package/dist/builtins/local-auth/auth-schema.d.ts.map +1 -0
  107. package/dist/builtins/local-auth/index.d.ts +2 -0
  108. package/dist/builtins/local-auth/index.d.ts.map +1 -0
  109. package/dist/builtins/local-auth/index.js +3 -623
  110. package/dist/builtins/local-auth/index.mjs +2 -8
  111. package/dist/builtins/local-auth/local-auth.addon.d.ts +17 -0
  112. package/dist/builtins/local-auth/local-auth.addon.d.ts.map +1 -0
  113. package/dist/builtins/local-auth/local-auth.addon.js +6861 -589
  114. package/dist/builtins/local-auth/local-auth.addon.js.map +1 -1
  115. package/dist/builtins/local-auth/local-auth.addon.mjs +6883 -7
  116. package/dist/builtins/local-auth/local-auth.addon.mjs.map +1 -1
  117. package/dist/builtins/local-network/index.d.ts +3 -0
  118. package/dist/builtins/local-network/index.d.ts.map +1 -0
  119. package/dist/builtins/local-network/index.js +9 -0
  120. package/dist/builtins/local-network/index.mjs +2 -0
  121. package/dist/builtins/local-network/local-network.addon.d.ts +102 -0
  122. package/dist/builtins/local-network/local-network.addon.d.ts.map +1 -0
  123. package/dist/builtins/local-network/local-network.addon.js +404 -0
  124. package/dist/builtins/local-network/local-network.addon.js.map +1 -0
  125. package/dist/builtins/local-network/local-network.addon.mjs +392 -0
  126. package/dist/builtins/local-network/local-network.addon.mjs.map +1 -0
  127. package/dist/builtins/mesh-orchestrator/index.d.ts +2 -0
  128. package/dist/builtins/mesh-orchestrator/index.d.ts.map +1 -0
  129. package/dist/builtins/mesh-orchestrator/index.js +7 -0
  130. package/dist/builtins/mesh-orchestrator/index.mjs +2 -0
  131. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.d.ts +9 -0
  132. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.d.ts.map +1 -0
  133. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.js +83 -0
  134. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.js.map +1 -0
  135. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.mjs +77 -0
  136. package/dist/builtins/mesh-orchestrator/mesh-orchestrator.addon.mjs.map +1 -0
  137. package/dist/builtins/native-metrics/index.d.ts +3 -0
  138. package/dist/builtins/native-metrics/index.d.ts.map +1 -0
  139. package/dist/builtins/native-metrics/native-metrics-provider.d.ts +49 -0
  140. package/dist/builtins/native-metrics/native-metrics-provider.d.ts.map +1 -0
  141. package/dist/builtins/native-metrics/native-metrics.addon.d.ts +74 -0
  142. package/dist/builtins/native-metrics/native-metrics.addon.d.ts.map +1 -0
  143. package/dist/builtins/native-metrics/native-metrics.addon.js +887 -861
  144. package/dist/builtins/native-metrics/native-metrics.addon.js.map +1 -1
  145. package/dist/builtins/native-metrics/native-metrics.addon.mjs +914 -5
  146. package/dist/builtins/native-metrics/native-metrics.addon.mjs.map +1 -1
  147. package/dist/builtins/platform-probe/index.d.ts +12 -0
  148. package/dist/builtins/platform-probe/index.d.ts.map +1 -0
  149. package/dist/builtins/platform-probe/index.js +539 -0
  150. package/dist/builtins/platform-probe/index.js.map +1 -0
  151. package/dist/builtins/platform-probe/index.mjs +530 -0
  152. package/dist/builtins/platform-probe/index.mjs.map +1 -0
  153. package/dist/builtins/platform-probe/inference-config-resolver.d.ts +30 -0
  154. package/dist/builtins/platform-probe/inference-config-resolver.d.ts.map +1 -0
  155. package/dist/builtins/platform-probe/platform-scorer.d.ts +22 -0
  156. package/dist/builtins/platform-probe/platform-scorer.d.ts.map +1 -0
  157. package/dist/builtins/remote-access-orchestrator/index.d.ts +2 -0
  158. package/dist/builtins/remote-access-orchestrator/index.d.ts.map +1 -0
  159. package/dist/builtins/remote-access-orchestrator/index.js +7 -0
  160. package/dist/builtins/remote-access-orchestrator/index.mjs +2 -0
  161. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts +9 -0
  162. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.d.ts.map +1 -0
  163. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +72 -0
  164. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js.map +1 -0
  165. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +66 -0
  166. package/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs.map +1 -0
  167. package/dist/builtins/snapshot/index.d.ts +3 -0
  168. package/dist/builtins/snapshot/index.d.ts.map +1 -0
  169. package/dist/builtins/snapshot/index.js +481 -491
  170. package/dist/builtins/snapshot/index.js.map +1 -1
  171. package/dist/builtins/snapshot/index.mjs +475 -464
  172. package/dist/builtins/snapshot/index.mjs.map +1 -1
  173. package/dist/builtins/snapshot/snapshot.addon.d.ts +121 -0
  174. package/dist/builtins/snapshot/snapshot.addon.d.ts.map +1 -0
  175. package/dist/builtins/sqlite-storage/config-store.d.ts +9 -0
  176. package/dist/builtins/sqlite-storage/config-store.d.ts.map +1 -0
  177. package/dist/builtins/sqlite-storage/device-store.d.ts +24 -0
  178. package/dist/builtins/sqlite-storage/device-store.d.ts.map +1 -0
  179. package/dist/builtins/sqlite-storage/filesystem-storage-provider.d.ts +87 -0
  180. package/dist/builtins/sqlite-storage/filesystem-storage-provider.d.ts.map +1 -0
  181. package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +32 -0
  182. package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts.map +1 -0
  183. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +312 -56
  184. package/dist/builtins/sqlite-storage/filesystem-storage.addon.js.map +1 -1
  185. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +305 -7
  186. package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs.map +1 -1
  187. package/dist/builtins/sqlite-storage/index.d.ts +12 -0
  188. package/dist/builtins/sqlite-storage/index.d.ts.map +1 -0
  189. package/dist/builtins/sqlite-storage/index.js +229 -1001
  190. package/dist/builtins/sqlite-storage/index.js.map +1 -1
  191. package/dist/builtins/sqlite-storage/index.mjs +268 -26
  192. package/dist/builtins/sqlite-storage/index.mjs.map +1 -1
  193. package/dist/builtins/sqlite-storage/integration-registry.d.ts +28 -0
  194. package/dist/builtins/sqlite-storage/integration-registry.d.ts.map +1 -0
  195. package/dist/builtins/sqlite-storage/settings-store.d.ts +40 -0
  196. package/dist/builtins/sqlite-storage/settings-store.d.ts.map +1 -0
  197. package/dist/builtins/sqlite-storage/sql-schema.d.ts +33 -0
  198. package/dist/builtins/sqlite-storage/sql-schema.d.ts.map +1 -0
  199. package/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts +94 -0
  200. package/dist/builtins/sqlite-storage/sqlite-settings-backend.d.ts.map +1 -0
  201. package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +15 -0
  202. package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts.map +1 -0
  203. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +586 -653
  204. package/dist/builtins/sqlite-storage/sqlite-settings.addon.js.map +1 -1
  205. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +582 -7
  206. package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs.map +1 -1
  207. package/dist/builtins/storage-orchestrator/index.d.ts +7 -0
  208. package/dist/builtins/storage-orchestrator/index.d.ts.map +1 -0
  209. package/dist/builtins/storage-orchestrator/index.js +9 -0
  210. package/dist/builtins/storage-orchestrator/index.mjs +2 -0
  211. package/dist/builtins/storage-orchestrator/location-store.d.ts +50 -0
  212. package/dist/builtins/storage-orchestrator/location-store.d.ts.map +1 -0
  213. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts +60 -0
  214. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.d.ts.map +1 -0
  215. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +755 -0
  216. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js.map +1 -0
  217. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +746 -0
  218. package/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs.map +1 -0
  219. package/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts +121 -0
  220. package/dist/builtins/storage-orchestrator/storage-orchestrator.service.d.ts.map +1 -0
  221. package/dist/builtins/system-backup/system-backup.service.d.ts +138 -0
  222. package/dist/builtins/system-backup/system-backup.service.d.ts.map +1 -0
  223. package/dist/builtins/system-config/index.d.ts +2 -0
  224. package/dist/builtins/system-config/index.d.ts.map +1 -0
  225. package/dist/builtins/system-config/index.js +6 -188
  226. package/dist/builtins/system-config/index.mjs +2 -10
  227. package/dist/builtins/system-config/system-config.addon.d.ts +11 -0
  228. package/dist/builtins/system-config/system-config.addon.d.ts.map +1 -0
  229. package/dist/builtins/system-config/system-config.addon.js +227 -180
  230. package/dist/builtins/system-config/system-config.addon.js.map +1 -1
  231. package/dist/builtins/system-config/system-config.addon.mjs +226 -7
  232. package/dist/builtins/system-config/system-config.addon.mjs.map +1 -1
  233. package/dist/builtins/turn-orchestrator/index.d.ts +2 -0
  234. package/dist/builtins/turn-orchestrator/index.d.ts.map +1 -0
  235. package/dist/builtins/turn-orchestrator/index.js +7 -0
  236. package/dist/builtins/turn-orchestrator/index.mjs +2 -0
  237. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.d.ts +10 -0
  238. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.d.ts.map +1 -0
  239. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.js +78 -0
  240. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.js.map +1 -0
  241. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.mjs +72 -0
  242. package/dist/builtins/turn-orchestrator/turn-orchestrator.addon.mjs.map +1 -0
  243. package/dist/builtins/winston-logging/index.d.ts +4 -0
  244. package/dist/builtins/winston-logging/index.d.ts.map +1 -0
  245. package/dist/builtins/winston-logging/index.js +153 -300
  246. package/dist/builtins/winston-logging/index.js.map +1 -1
  247. package/dist/builtins/winston-logging/index.mjs +144 -9
  248. package/dist/builtins/winston-logging/index.mjs.map +1 -1
  249. package/dist/builtins/winston-logging/winston-destination.d.ts +22 -0
  250. package/dist/builtins/winston-logging/winston-destination.d.ts.map +1 -0
  251. package/dist/builtins/winston-logging/winston-logging.addon.d.ts +20 -0
  252. package/dist/builtins/winston-logging/winston-logging.addon.d.ts.map +1 -0
  253. package/dist/chunk-C13QxCFV.js +50 -0
  254. package/dist/chunk-hT5z_Zn9.mjs +35 -0
  255. package/dist/download/model-download-service.d.ts +42 -0
  256. package/dist/download/model-download-service.d.ts.map +1 -0
  257. package/dist/download/model-downloader.d.ts +32 -0
  258. package/dist/download/model-downloader.d.ts.map +1 -0
  259. package/dist/events/event-bus.d.ts +11 -0
  260. package/dist/events/event-bus.d.ts.map +1 -0
  261. package/dist/events/system-event-bus.d.ts +15 -0
  262. package/dist/events/system-event-bus.d.ts.map +1 -0
  263. package/dist/feature/feature-manager.d.ts +12 -0
  264. package/dist/feature/feature-manager.d.ts.map +1 -0
  265. package/dist/formatter-C-5An4Bl.mjs +164 -0
  266. package/dist/formatter-C-5An4Bl.mjs.map +1 -0
  267. package/dist/formatter-Dr_6NNZc.js +169 -0
  268. package/dist/formatter-Dr_6NNZc.js.map +1 -0
  269. package/dist/index.d.ts +76 -1696
  270. package/dist/index.d.ts.map +1 -0
  271. package/dist/index.js +7780 -8035
  272. package/dist/index.js.map +1 -1
  273. package/dist/index.mjs +7707 -2148
  274. package/dist/index.mjs.map +1 -1
  275. package/dist/lifecycle/lifecycle-state-machine.d.ts +29 -0
  276. package/dist/lifecycle/lifecycle-state-machine.d.ts.map +1 -0
  277. package/dist/logging/formatter.d.ts +31 -0
  278. package/dist/logging/formatter.d.ts.map +1 -0
  279. package/dist/logging/log-manager.d.ts +52 -0
  280. package/dist/logging/log-manager.d.ts.map +1 -0
  281. package/dist/logging/log-ring-buffer.d.ts +48 -0
  282. package/dist/logging/log-ring-buffer.d.ts.map +1 -0
  283. package/dist/logging/scoped-logger.d.ts +18 -0
  284. package/dist/logging/scoped-logger.d.ts.map +1 -0
  285. package/dist/network/network-quality.d.ts +12 -0
  286. package/dist/network/network-quality.d.ts.map +1 -0
  287. package/dist/notification/notification-service.d.ts +38 -0
  288. package/dist/notification/notification-service.d.ts.map +1 -0
  289. package/dist/notification/toast-service.d.ts +23 -0
  290. package/dist/notification/toast-service.d.ts.map +1 -0
  291. package/dist/pipeline/engine-manager-resolver.d.ts +16 -0
  292. package/dist/pipeline/engine-manager-resolver.d.ts.map +1 -0
  293. package/dist/pipeline/pipeline-runner.d.ts +9 -0
  294. package/dist/pipeline/pipeline-runner.d.ts.map +1 -0
  295. package/dist/pipeline/pipeline-validator.d.ts +14 -0
  296. package/dist/pipeline/pipeline-validator.d.ts.map +1 -0
  297. package/dist/process/resource-monitor.d.ts +12 -0
  298. package/dist/process/resource-monitor.d.ts.map +1 -0
  299. package/dist/python/python-env-manager.d.ts +13 -0
  300. package/dist/python/python-env-manager.d.ts.map +1 -0
  301. package/dist/repl/interfaces.d.ts +32 -0
  302. package/dist/repl/interfaces.d.ts.map +1 -0
  303. package/dist/repl/repl-engine.d.ts +9 -0
  304. package/dist/repl/repl-engine.d.ts.map +1 -0
  305. package/dist/resource-monitor-CmuWlmap.js +76 -0
  306. package/dist/resource-monitor-CmuWlmap.js.map +1 -0
  307. package/dist/resource-monitor-DcQdKGYU.mjs +59 -0
  308. package/dist/resource-monitor-DcQdKGYU.mjs.map +1 -0
  309. package/dist/storage/fs-storage-backend.d.ts +41 -0
  310. package/dist/storage/fs-storage-backend.d.ts.map +1 -0
  311. package/dist/storage/storage-location-manager.d.ts +24 -0
  312. package/dist/storage/storage-location-manager.d.ts.map +1 -0
  313. package/dist/storage/storage-manager.d.ts +77 -0
  314. package/dist/storage/storage-manager.d.ts.map +1 -0
  315. package/dist/tls/cert-manager.d.ts +27 -0
  316. package/dist/tls/cert-manager.d.ts.map +1 -0
  317. package/dist/tls/index.d.ts +2 -0
  318. package/dist/tls/index.d.ts.map +1 -0
  319. package/package.json +119 -23
  320. package/dist/builtins/addon-pages-aggregator/index.js.map +0 -1
  321. package/dist/builtins/addon-pages-aggregator/index.mjs.map +0 -1
  322. package/dist/builtins/addon-widgets-aggregator/index.js.map +0 -1
  323. package/dist/builtins/addon-widgets-aggregator/index.mjs.map +0 -1
  324. package/dist/builtins/alerts/index.js.map +0 -1
  325. package/dist/builtins/alerts/index.mjs.map +0 -1
  326. package/dist/builtins/device-manager/index.js.map +0 -1
  327. package/dist/builtins/device-manager/index.mjs.map +0 -1
  328. package/dist/builtins/local-auth/index.js.map +0 -1
  329. package/dist/builtins/local-auth/index.mjs.map +0 -1
  330. package/dist/builtins/local-backup/index.js +0 -173
  331. package/dist/builtins/local-backup/index.js.map +0 -1
  332. package/dist/builtins/local-backup/index.mjs +0 -10
  333. package/dist/builtins/local-backup/index.mjs.map +0 -1
  334. package/dist/builtins/system-config/index.js.map +0 -1
  335. package/dist/builtins/system-config/index.mjs.map +0 -1
  336. package/dist/chunk-2CIYKDRN.mjs +0 -1
  337. package/dist/chunk-2CIYKDRN.mjs.map +0 -1
  338. package/dist/chunk-2F76X6NL.mjs +0 -136
  339. package/dist/chunk-2F76X6NL.mjs.map +0 -1
  340. package/dist/chunk-2QUFBZ7M.mjs +0 -1
  341. package/dist/chunk-2QUFBZ7M.mjs.map +0 -1
  342. package/dist/chunk-3BK2Y7GY.mjs +0 -593
  343. package/dist/chunk-3BK2Y7GY.mjs.map +0 -1
  344. package/dist/chunk-4OOHFJHT.mjs +0 -421
  345. package/dist/chunk-4OOHFJHT.mjs.map +0 -1
  346. package/dist/chunk-4XHB7IHT.mjs +0 -809
  347. package/dist/chunk-4XHB7IHT.mjs.map +0 -1
  348. package/dist/chunk-6M2HSSTQ.mjs +0 -98
  349. package/dist/chunk-6M2HSSTQ.mjs.map +0 -1
  350. package/dist/chunk-7FI7SQS7.mjs +0 -135
  351. package/dist/chunk-7FI7SQS7.mjs.map +0 -1
  352. package/dist/chunk-ED57RCQE.mjs +0 -171
  353. package/dist/chunk-ED57RCQE.mjs.map +0 -1
  354. package/dist/chunk-FZN56HGQ.mjs +0 -626
  355. package/dist/chunk-FZN56HGQ.mjs.map +0 -1
  356. package/dist/chunk-GL4OOB25.mjs +0 -51
  357. package/dist/chunk-GL4OOB25.mjs.map +0 -1
  358. package/dist/chunk-KDG2NTDB.mjs +0 -137
  359. package/dist/chunk-KDG2NTDB.mjs.map +0 -1
  360. package/dist/chunk-NRBQWBDM.mjs +0 -191
  361. package/dist/chunk-NRBQWBDM.mjs.map +0 -1
  362. package/dist/chunk-O4V246GG.mjs +0 -2137
  363. package/dist/chunk-O4V246GG.mjs.map +0 -1
  364. package/dist/chunk-QT57H266.mjs +0 -163
  365. package/dist/chunk-QT57H266.mjs.map +0 -1
  366. package/dist/chunk-QX4RH25I.mjs +0 -141
  367. package/dist/chunk-QX4RH25I.mjs.map +0 -1
  368. package/dist/chunk-TB562PZX.mjs +0 -86
  369. package/dist/chunk-TB562PZX.mjs.map +0 -1
  370. package/dist/chunk-TDYPZXK5.mjs +0 -1
  371. package/dist/chunk-TDYPZXK5.mjs.map +0 -1
  372. package/dist/chunk-UJI4LN5P.mjs +0 -36
  373. package/dist/chunk-UJI4LN5P.mjs.map +0 -1
  374. package/dist/chunk-W6RTHQGP.mjs +0 -1
  375. package/dist/chunk-W6RTHQGP.mjs.map +0 -1
  376. package/dist/chunk-ZELBCPDC.mjs +0 -369
  377. package/dist/chunk-ZELBCPDC.mjs.map +0 -1
  378. package/dist/index.d.mts +0 -1696
  379. package/dist/resource-monitor-UZUGPIAU.mjs +0 -9
  380. package/dist/resource-monitor-UZUGPIAU.mjs.map +0 -1
  381. package/dist/storage-location-manager-HFNB3PCS.mjs +0 -7
  382. package/dist/storage-location-manager-HFNB3PCS.mjs.map +0 -1
@@ -1,2157 +1,7 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/builtins/device-manager/index.ts
21
- var device_manager_exports = {};
22
- __export(device_manager_exports, {
23
- DeviceManagerAddon: () => DeviceManagerAddon,
24
- default: () => device_manager_addon_default
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
25
4
  });
26
- module.exports = __toCommonJS(device_manager_exports);
27
-
28
- // src/builtins/device-manager/device-manager.addon.ts
29
- var import_node_crypto = require("crypto");
30
- var import_types = require("@camstack/types");
31
-
32
- // src/builtins/device-manager/device-event-propagator.ts
33
- var MAX_CHAIN_DEPTH = 16;
34
- var DeviceEventPropagator = class {
35
- constructor(opts) {
36
- this.opts = opts;
37
- }
38
- opts;
39
- unsubscribe = null;
40
- start() {
41
- if (this.unsubscribe) return;
42
- const unsub = this.opts.eventBus.subscribe({}, (ev) => this.handle(ev));
43
- this.unsubscribe = unsub;
44
- }
45
- stop() {
46
- if (!this.unsubscribe) return;
47
- this.unsubscribe();
48
- this.unsubscribe = null;
49
- }
50
- /** Exposed for tests — lets them inject events without the full bus. */
51
- handle(ev) {
52
- if (ev.via !== void 0) return;
53
- if (ev.source.type !== "device") return;
54
- const rawId = ev.source.id;
55
- const deviceId = typeof rawId === "number" ? rawId : Number(rawId);
56
- if (!Number.isFinite(deviceId)) return;
57
- const chain = this.resolveParentChain(deviceId);
58
- if (chain.length === 0) return;
59
- const origin = ev.source;
60
- const via = [origin];
61
- for (const ancestorId of chain) {
62
- const reEmission = {
63
- ...ev,
64
- source: { type: "device", id: ancestorId },
65
- via: [...via]
66
- };
67
- this.opts.eventBus.emit(reEmission);
68
- via.push({ type: "device", id: ancestorId });
69
- }
70
- }
71
- resolveParentChain(deviceId) {
72
- const chain = [];
73
- const seen = /* @__PURE__ */ new Set([deviceId]);
74
- let current = this.opts.getParentOf(deviceId);
75
- while (current != null) {
76
- if (seen.has(current)) {
77
- this.opts.logger.warn(
78
- "device-event-propagator: cycle detected in parent chain \u2014 aborting propagation",
79
- { tags: { deviceId }, meta: { cycleAt: current, chainSoFar: [...chain] } }
80
- );
81
- return chain;
82
- }
83
- seen.add(current);
84
- chain.push(current);
85
- if (chain.length >= MAX_CHAIN_DEPTH) {
86
- this.opts.logger.warn(
87
- "device-event-propagator: chain depth limit hit \u2014 truncating",
88
- { tags: { deviceId }, meta: { depth: chain.length, max: MAX_CHAIN_DEPTH } }
89
- );
90
- break;
91
- }
92
- current = this.opts.getParentOf(current);
93
- }
94
- return chain;
95
- }
96
- };
97
-
98
- // src/builtins/device-manager/device-manager.addon.ts
99
- var import_types2 = require("@camstack/types");
100
- var import_types3 = require("@camstack/types");
101
- var import_types4 = require("@camstack/types");
102
- function shallowEqual(a, b) {
103
- const ak = Object.keys(a);
104
- const bk = Object.keys(b);
105
- if (ak.length !== bk.length) return false;
106
- for (const k of ak) {
107
- if (a[k] !== b[k]) return false;
108
- }
109
- return true;
110
- }
111
- function deviceKey(addonId, stableId) {
112
- return `${addonId}:${stableId}`;
113
- }
114
- function isCameraDevice(device) {
115
- return "getStreamSources" in device && typeof device.getStreamSources === "function";
116
- }
117
- var DEVICE_FEATURE_VALUES = new Set(Object.values(import_types.DeviceFeature));
118
- function persistedFeatures(features) {
119
- if (!features) return [];
120
- const out = [];
121
- for (const f of features) {
122
- if (DEVICE_FEATURE_VALUES.has(f)) out.push(f);
123
- }
124
- return out;
125
- }
126
- function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
127
- const configValues = {};
128
- for (const entry of device.config.entries()) {
129
- configValues[entry.key] = entry.value;
130
- }
131
- const name = metaRow?.name ?? device.name;
132
- const location = metaRow?.location !== void 0 ? metaRow.location : device.location;
133
- const disabled = metaRow?.disabled ?? device.disabled;
134
- return {
135
- // Progressive system-wide id — bound on the live `IDevice` at
136
- // construction time (see `DeviceContext.id` / `BaseDevice.id`). The
137
- // hub allocates via `allocateDeviceId` BEFORE the device is
138
- // instantiated, so every live device exposes one.
139
- id: device.id,
140
- stableId: device.stableId,
141
- addonId,
142
- type: device.type,
143
- name,
144
- location,
145
- disabled,
146
- parentDeviceId: device.parentDeviceId,
147
- // `role` is set by the provider on accessory children (synthesized
148
- // via `getAccessoryChildren()` — Reolink siren/floodlight/PIR,
149
- // Hikvision supplemental light/siren). Top-level devices and
150
- // first-class hub-adopted children leave it `undefined`. Surfacing
151
- // it on `DeviceInfo` lets the UI distinguish accessory rows from
152
- // adopted-camera rows without re-deriving the heuristic from the
153
- // provider's `deviceClasses` map.
154
- role: device.role ?? null,
155
- online: device.online,
156
- features: [...device.features],
157
- isCamera: isCameraDevice(device),
158
- config: configValues,
159
- metadata
160
- };
161
- }
162
- function resolveDeviceById(registry, deviceId) {
163
- const device = registry.getById(deviceId);
164
- if (!device) return null;
165
- const addonId = registry.getAddonId(deviceId);
166
- if (!addonId) return null;
167
- return { addonId, device };
168
- }
169
- function tagContribution(contribution, capName, addonId, kind) {
170
- const source = kind === "settings" ? "settings" : "live";
171
- return {
172
- ...contribution.tabs ? { tabs: [...contribution.tabs] } : {},
173
- sections: contribution.sections.map((section) => ({
174
- ...section,
175
- fields: section.fields.map((field) => tagField(field, capName, addonId, source, kind))
176
- }))
177
- };
178
- }
179
- function isFieldRecord(value) {
180
- return value !== null && typeof value === "object" && !Array.isArray(value);
181
- }
182
- function toWireShape(input) {
183
- const out = {
184
- sections: input.sections.map((s) => ({
185
- id: s.id,
186
- title: s.title,
187
- ...s.description !== void 0 ? { description: s.description } : {},
188
- ...s.style !== void 0 ? { style: s.style } : {},
189
- ...s.defaultCollapsed !== void 0 ? { defaultCollapsed: s.defaultCollapsed } : {},
190
- ...s.columns !== void 0 ? { columns: s.columns } : {},
191
- ...s.tab !== void 0 ? { tab: s.tab } : {},
192
- // `location: 'top-tab'` hoists the section into a discovered top-
193
- // level device tab in DeviceDetail. Forgetting to forward it here
194
- // strips the marker before the client sees it, so the tab never
195
- // shows up — see `DeviceDetail.tsx` aggregate-driven tab discovery.
196
- ...s.location !== void 0 ? { location: s.location } : {},
197
- ...s.order !== void 0 ? { order: s.order } : {},
198
- fields: [...s.fields]
199
- }))
200
- };
201
- if (input.tabs) out.tabs = [...input.tabs];
202
- return out;
203
- }
204
- function tagField(field, capName, addonId, source, kind) {
205
- if (!isFieldRecord(field)) return field;
206
- const f = field;
207
- const structuralTypes = /* @__PURE__ */ new Set(["separator", "info", "button"]);
208
- if (typeof f.type === "string" && structuralTypes.has(f.type)) return field;
209
- const tagged = { ...f, source };
210
- if (kind === "live" || f.readonlyField === true) {
211
- tagged.readonlyField = true;
212
- } else {
213
- tagged.writerCapName = capName;
214
- tagged.writerAddonId = addonId;
215
- }
216
- if (f.type === "group") {
217
- const children = Array.isArray(f.fields) ? f.fields : [];
218
- if (children.length > 0) {
219
- tagged.fields = children.map((child) => tagField(child, capName, addonId, source, kind));
220
- }
221
- } else if (f.type === "sub-tabs") {
222
- const rawTabs = Array.isArray(f.tabs) ? f.tabs : [];
223
- if (rawTabs.length > 0) {
224
- tagged.tabs = rawTabs.map((tab) => {
225
- if (!isFieldRecord(tab)) return tab;
226
- const tabChildren = Array.isArray(tab.fields) ? tab.fields : [];
227
- return {
228
- ...tab,
229
- fields: tabChildren.map((child) => tagField(child, capName, addonId, source, kind))
230
- };
231
- });
232
- }
233
- }
234
- return tagged;
235
- }
236
- function mergeAggregates(parts) {
237
- const tabDecls = /* @__PURE__ */ new Map();
238
- const sections = [];
239
- for (const part of parts) {
240
- if (part.tabs) {
241
- for (const t of part.tabs) {
242
- if (!tabDecls.has(t.id)) tabDecls.set(t.id, t);
243
- }
244
- }
245
- for (const s of part.sections) {
246
- sections.push(s);
247
- }
248
- }
249
- for (const s of sections) {
250
- const tabId = s.tab ?? "general";
251
- if (tabDecls.has(tabId)) continue;
252
- const known = import_types3.WELL_KNOWN_TAB_MAP[tabId];
253
- if (known) {
254
- tabDecls.set(tabId, { id: known.id, label: known.label, icon: known.icon, order: known.order });
255
- } else {
256
- tabDecls.set(tabId, { id: tabId, label: tabId, icon: "wrench", order: 100 });
257
- }
258
- }
259
- sections.sort((a, b) => {
260
- const tabA = a.tab ?? "general";
261
- const tabB = b.tab ?? "general";
262
- if (tabA !== tabB) {
263
- const orderA = tabDecls.get(tabA)?.order ?? 100;
264
- const orderB = tabDecls.get(tabB)?.order ?? 100;
265
- if (orderA !== orderB) return orderA - orderB;
266
- return tabA.localeCompare(tabB);
267
- }
268
- return (a.order ?? 0) - (b.order ?? 0);
269
- });
270
- const sortedTabs = [...tabDecls.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
271
- const out = { sections };
272
- if (sortedTabs.length > 0) out.tabs = sortedTabs;
273
- return out;
274
- }
275
- var DeviceManagerAddon = class _DeviceManagerAddon extends import_types.BaseAddon {
276
- constructor() {
277
- super({});
278
- }
279
- /** Shorthand for the kernel-injected capability registry. */
280
- get capabilityRegistry() {
281
- return this.ctx.kernel.capabilityRegistry;
282
- }
283
- /**
284
- * Parent-chain event propagator. Started in `onInitialize` once the
285
- * hub's `deviceRegistry` is available; listens to every device-sourced
286
- * event and re-emits a copy on each ancestor scope with `via[]`
287
- * populated. Stopped in `onShutdown`.
288
- */
289
- propagator = null;
290
- /**
291
- * Hub-side mirror of every device's cap-keyed runtime state.
292
- * Populated whenever any caller writes via `deviceState.setCapSlice`
293
- * (the canonical cross-layer write entrypoint) and on first load
294
- * via `loadRuntimeState`. Cross-process consumers reach the mirror
295
- * through the `deviceState` cap router; per-cap event subscribers
296
- * (e.g. `battery.onStatusChanged`) get the same data via
297
- * cap-specific events still emitted by the owning device.
298
- *
299
- * Key: deviceId. Value: per-cap slice map. Empty by default —
300
- * slices show up as `setCapSlice` calls trickle in.
301
- */
302
- stateMirror = /* @__PURE__ */ new Map();
303
- /**
304
- * Per-device disk-write debouncer for runtime-state. `setCapSlice`
305
- * updates the in-memory mirror synchronously and emits the change
306
- * event immediately, but the disk write is coalesced — frequent
307
- * back-to-back writes (motion phase transitions, battery pushes,
308
- * etc.) collapse to one `writeDeviceRuntimeState` per
309
- * `RUNTIME_STATE_DEBOUNCE_MS` window. `flushRuntimeStateWrites`
310
- * awaits any in-flight write + scheduled flush so shutdown is
311
- * lossless.
312
- */
313
- runtimeStateDebounce = /* @__PURE__ */ new Map();
314
- static RUNTIME_STATE_DEBOUNCE_MS = 1e3;
315
- /**
316
- * Cross-process native-provider cache: deviceId (numeric) → capName → { addonId, nodeId }.
317
- * Kept in sync with `device.bindings-changed` events emitted by forked
318
- * workers. Union'd into `getBindings` so hub-side consumers see every
319
- * native cap regardless of which process owns the IDevice. No persistence
320
- * — entries re-register when the worker restarts. Purged on
321
- * `$node.disconnected` to avoid stale routing after a worker crash.
322
- */
323
- remoteNativeCaps = /* @__PURE__ */ new Map();
324
- /** Wait for a device-provider by addonId, returning null on timeout. */
325
- async waitDeviceProvider(addonId, timeoutMs = 5e3) {
326
- const provider = await this.capabilityRegistry?.waitForProvider("device-provider", addonId, timeoutMs);
327
- return provider ? provider : null;
328
- }
329
- /** Require a device-provider by addonId — throws if not found. */
330
- async requireDeviceProvider(addonId) {
331
- const dp = await this.waitDeviceProvider(addonId);
332
- if (!dp) {
333
- throw new Error(`Device provider "${addonId}" not found or not registered`);
334
- }
335
- return dp;
336
- }
337
- // ── Binding store (persisted wrapper activation) ───────────────────────────
338
- //
339
- // These methods are public so the device-manager capability router can
340
- // expose them as cap methods. They read/write through
341
- // ctx.settings.readAddonStore/writeAddonStore — the same persistence channel
342
- // the rest of the addon uses.
343
- async readBindingsStore() {
344
- const raw = await this.ctx.settings.readAddonStore();
345
- return { deviceBindings: raw.deviceBindings ?? {} };
346
- }
347
- async writeBindingsStore(next) {
348
- await this.ctx.settings.writeAddonStore({ deviceBindings: next.deviceBindings });
349
- }
350
- resolveWrapperNodeId(_wrapperAddonId) {
351
- return "hub";
352
- }
353
- /**
354
- * Active discovery of native caps registered on a worker node.
355
- * Called from the `$node.connected` handler to recover from lost
356
- * `DeviceBindingsChanged` broadcasts after worker restart.
357
- *
358
- * Iterates the broker's service registry, picks
359
- * `<addonId>.native-provider.<capName>` services owned by the
360
- * connected node, calls each service's `$listDeviceIds` action to
361
- * fetch the deviceIds the worker has registered that cap on, then
362
- * writes entries into `remoteNativeCaps`.
363
- *
364
- * Best-effort: per-service failures are logged and swallowed so a
365
- * single bad service doesn't abort the whole rebuild.
366
- */
367
- async discoverWorkerNativeCaps(connectedNodeId, _connectedAddonId) {
368
- const cluster = this.ctx.kernel.cluster;
369
- if (!cluster) return;
370
- const broker = cluster.broker;
371
- const services = broker.registry?.getServiceList?.({ onlyAvailable: true, withActions: false }) ?? [];
372
- const NATIVE_INFIX = ".native-provider.";
373
- const matched = services.filter(
374
- (s) => s.nodeID === connectedNodeId && s.name.includes(NATIVE_INFIX)
375
- );
376
- if (matched.length === 0) return;
377
- for (const svc of matched) {
378
- const idx = svc.name.indexOf(NATIVE_INFIX);
379
- if (idx <= 0) continue;
380
- const addonId = svc.name.slice(0, idx);
381
- const capName = svc.name.slice(idx + NATIVE_INFIX.length);
382
- if (!addonId || !capName) continue;
383
- try {
384
- const action = `${svc.name}.$listDeviceIds`;
385
- const deviceIds = await broker.call?.(action, {}, { nodeID: connectedNodeId });
386
- if (!deviceIds || deviceIds.length === 0) continue;
387
- for (const deviceId of deviceIds) {
388
- if (this.capabilityRegistry?.getNativeAddonId(capName, deviceId)) continue;
389
- let perDevice = this.remoteNativeCaps.get(deviceId);
390
- if (!perDevice) {
391
- perDevice = /* @__PURE__ */ new Map();
392
- this.remoteNativeCaps.set(deviceId, perDevice);
393
- }
394
- perDevice.set(capName, { addonId, nodeId: connectedNodeId });
395
- }
396
- this.ctx.logger.debug("worker native-cap discovered", {
397
- meta: { nodeId: connectedNodeId, addonId, capName, deviceIds }
398
- });
399
- } catch (err) {
400
- this.ctx.logger.debug("worker native-cap $listDeviceIds failed", {
401
- meta: { service: svc.name, nodeId: connectedNodeId, error: (0, import_types.errMsg)(err) }
402
- });
403
- }
404
- }
405
- this.ctx.logger.info("worker native-cap discovery completed", {
406
- meta: { nodeId: connectedNodeId, services: matched.length }
407
- });
408
- }
409
- async getBindings(input) {
410
- const storeKey = String(input.deviceId);
411
- const store = await this.readBindingsStore();
412
- const perDevice = store.deviceBindings[storeKey] ?? {};
413
- const entries = [];
414
- const seenCaps = /* @__PURE__ */ new Set();
415
- for (const [capName, { wrapperAddonId }] of Object.entries(perDevice)) {
416
- const hubLocalNative = this.capabilityRegistry?.getNativeAddonId(capName, input.deviceId) ?? null;
417
- const remoteNative = this.remoteNativeCaps.get(input.deviceId)?.get(capName) ?? null;
418
- const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
419
- const nativeNodeId = hubLocalNative ? this.ctx.kernel.localNodeId ?? "hub" : remoteNative?.nodeId ?? (this.ctx.kernel.localNodeId ?? "hub");
420
- if (wrapperAddonId === null && !nativeAddonId) {
421
- seenCaps.add(capName);
422
- continue;
423
- }
424
- entries.push({
425
- capName,
426
- kind: wrapperAddonId ? "wrapped" : "native",
427
- providerAddonId: wrapperAddonId ?? nativeAddonId,
428
- providerNodeId: wrapperAddonId ? this.resolveWrapperNodeId(wrapperAddonId) : nativeNodeId,
429
- nativeAddonId
430
- });
431
- seenCaps.add(capName);
432
- }
433
- const remote = this.remoteNativeCaps.get(input.deviceId);
434
- if (this.capabilityRegistry) {
435
- for (const capName of this.capabilityRegistry.getCapsWithDefaultWrapper()) {
436
- if (seenCaps.has(capName)) continue;
437
- const defaultWrapperAddonId = this.capabilityRegistry.getDefaultWrapperForCap(capName);
438
- if (!defaultWrapperAddonId) continue;
439
- const hubLocalNative = this.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? null;
440
- const remoteNative = remote?.get(capName) ?? null;
441
- const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
442
- entries.push({
443
- capName,
444
- kind: "wrapped",
445
- providerAddonId: defaultWrapperAddonId,
446
- providerNodeId: this.resolveWrapperNodeId(defaultWrapperAddonId),
447
- nativeAddonId
448
- });
449
- seenCaps.add(capName);
450
- }
451
- }
452
- if (this.capabilityRegistry) {
453
- for (const capName of this.capabilityRegistry.getNativeCapsForDevice(input.deviceId)) {
454
- if (seenCaps.has(capName)) continue;
455
- const nativeAddonId = this.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? "";
456
- entries.push({
457
- capName,
458
- kind: "native",
459
- providerAddonId: nativeAddonId,
460
- providerNodeId: this.ctx.kernel.localNodeId ?? "hub",
461
- nativeAddonId
462
- });
463
- seenCaps.add(capName);
464
- }
465
- }
466
- if (remote) {
467
- for (const [capName, info] of remote) {
468
- if (seenCaps.has(capName)) continue;
469
- entries.push({
470
- capName,
471
- kind: "native",
472
- providerAddonId: info.addonId,
473
- providerNodeId: info.nodeId,
474
- nativeAddonId: info.addonId
475
- });
476
- seenCaps.add(capName);
477
- }
478
- }
479
- return { deviceId: input.deviceId, entries };
480
- }
481
- /**
482
- * Whole-fleet binding dump. Iterates every device known to the
483
- * deviceRegistry and reuses the per-device `getBindings` resolver
484
- * for each — same routing rules, single round-trip. Used by
485
- * `SystemManager.init()` for warm-boot.
486
- *
487
- * Bindings change rarely (wrapper toggle, device add/remove) so
488
- * clients invalidate via the existing
489
- * `capability.binding-changed` event rather than re-fetching this
490
- * payload periodically.
491
- */
492
- async getAllBindings() {
493
- const hubRegistry = this.ctx.kernel?.deviceRegistry;
494
- if (!hubRegistry) return [];
495
- const out = [];
496
- for (const device of hubRegistry.getAll()) {
497
- out.push(await this.getBindings({ deviceId: device.id }));
498
- }
499
- return out;
500
- }
501
- /**
502
- * Resolve a numeric deviceId to a stableId via persisted meta.
503
- * Used only by the device-identity section of the device-details
504
- * aggregator (see `buildBaseDeviceSection`) to surface the stableId as
505
- * a readonly display field. All runtime/registry lookups are keyed by
506
- * numeric deviceId; this helper is display-only.
507
- */
508
- async lookupPersistedStableId(deviceId) {
509
- const store = await this.ctx.settings.readAddonStore();
510
- const meta = store.deviceMeta ?? {};
511
- for (const [key, m] of Object.entries(meta)) {
512
- if (m.id === deviceId) {
513
- const sep = key.indexOf(":");
514
- if (sep < 0) continue;
515
- return key.slice(sep + 1);
516
- }
517
- }
518
- return void 0;
519
- }
520
- // ── Device-details aggregator ──────────────────────────────────────────────
521
- //
522
- // Walks the bindings for `deviceId` (native + wrapped), picks every
523
- // provider whose cap declares `exposesDeviceSettings: true`, and asks
524
- // each for its per-device contribution. Contributions are concatenated
525
- // into a single `ConfigUISchemaWithValues`; editable fields are tagged
526
- // with `writerCapName` + `writerAddonId` so `updateDeviceField` can
527
- // route the mutation back to the exact provider that produced them.
528
- //
529
- // `kind` selects settings vs live-info. The two aggregators share the
530
- // enumeration + tagging pipeline; only the method invoked on each
531
- // contributing provider differs.
532
- async getDeviceAggregate(deviceId, kind) {
533
- const registry = this.capabilityRegistry;
534
- if (!registry) {
535
- this.ctx.logger.debug("capability registry unavailable \u2014 aggregate empty", { meta: { kind } });
536
- return null;
537
- }
538
- const method = kind === "settings" ? "getDeviceSettingsContribution" : "getDeviceLiveContribution";
539
- const contributors = [];
540
- for (const info of registry.listCapabilities()) {
541
- const def = registry.getDefinition(info.name);
542
- if (!def?.exposesDeviceSettings) continue;
543
- const seen = /* @__PURE__ */ new Set();
544
- const sorted = [...info.providers].sort((a, b) => a.length - b.length);
545
- for (const addonId of sorted) {
546
- if (addonId.includes("::native-")) continue;
547
- const baseId = addonId.includes("@") ? addonId.slice(0, addonId.indexOf("@")) : addonId;
548
- if (seen.has(baseId)) continue;
549
- seen.add(baseId);
550
- contributors.push({ capName: info.name, addonId });
551
- }
552
- }
553
- const results = await Promise.all(contributors.map(async ({ capName, addonId }) => {
554
- const provider = registry.getProviderByAddon(capName, addonId);
555
- if (!provider) {
556
- throw new Error(
557
- `[device-manager] capability "${capName}" lists provider "${addonId}" but getProviderByAddon returned null \u2014 registry inconsistency`
558
- );
559
- }
560
- try {
561
- const contribution = await provider[method]({ deviceId });
562
- if (!contribution) return null;
563
- return {
564
- capName,
565
- addonId,
566
- contribution: tagContribution(toWireShape(contribution), capName, addonId, kind)
567
- };
568
- } catch (err) {
569
- const msg = err instanceof Error ? err.message : String(err);
570
- this.ctx.logger.warn("contribution method failed", { tags: { deviceId, addonId }, meta: { capName, method, error: msg } });
571
- return null;
572
- }
573
- }));
574
- const base = kind === "settings" ? await this.buildBaseDeviceSection(deviceId) : null;
575
- const parts = [
576
- ...base ? [tagContribution(base, "device-manager", "device-manager", kind)] : [],
577
- ...results.filter((r) => r !== null).map((r) => r.contribution)
578
- ];
579
- if (parts.length === 0) return null;
580
- return mergeAggregates(parts);
581
- }
582
- /**
583
- * Build the device-manager's own contribution to the aggregator — the
584
- * device identity (id, stableId, addonId, type, online) + the
585
- * driver-specific config exposed by the device class via
586
- * `zodEntriesToConfigUI`.
587
- *
588
- * Two paths, deliberately symmetric with `getSettingsSchema`:
589
- *
590
- * - Hub-local: device's IDevice instance lives in this process'
591
- * DeviceRegistry, we read config + schema directly by reference.
592
- * - Cross-process: device lives in a forked worker (RtspCamera on
593
- * provider-rtsp, ONVIF on provider-onvif, …). We ask the worker's
594
- * `device-ops.getSettingsSchema` native provider for a wire-
595
- * serializable ConfigUISchema and merge it in under the same
596
- * "Driver Config" section, so the UI sees the same shape regardless
597
- * of where the IDevice physically runs.
598
- *
599
- * Returns `null` only when the device genuinely doesn't exist anywhere
600
- * (no hub-local, no persisted ownership, no device-ops native). The
601
- * aggregator falls back to contributor sections only in that case.
602
- */
603
- async buildBaseDeviceSection(deviceId) {
604
- const hubRegistry = this.ctx.kernel?.deviceRegistry;
605
- const hubLocal = hubRegistry ? resolveDeviceById(hubRegistry, deviceId) : null;
606
- const stableId = hubLocal?.device.stableId ?? await this.lookupPersistedStableId(deviceId);
607
- const nativeOwner = this.resolveNativeDeviceOwner(deviceId);
608
- const addonId = hubLocal?.addonId ?? nativeOwner?.addonId ?? null;
609
- if (!hubLocal && !nativeOwner) return null;
610
- const identityFields = [
611
- {
612
- type: "text",
613
- key: "_deviceId",
614
- label: "Device ID",
615
- readonlyField: true,
616
- value: String(deviceId)
617
- },
618
- {
619
- type: "text",
620
- key: "_stableId",
621
- label: "Stable ID",
622
- readonlyField: true,
623
- value: stableId ?? ""
624
- },
625
- {
626
- type: "text",
627
- key: "_addonId",
628
- label: "Driver",
629
- readonlyField: true,
630
- value: addonId ?? "unknown"
631
- },
632
- ...hubLocal ? [
633
- {
634
- type: "text",
635
- key: "_type",
636
- label: "Type",
637
- readonlyField: true,
638
- value: hubLocal.device.type
639
- },
640
- {
641
- type: "text",
642
- key: "_online",
643
- label: "Online",
644
- readonlyField: true,
645
- value: hubLocal.device.online ? "yes" : "no"
646
- }
647
- ] : []
648
- ];
649
- const sections = [
650
- {
651
- id: "device-identity",
652
- title: "Identity",
653
- tab: "general",
654
- order: 0,
655
- fields: identityFields
656
- }
657
- ];
658
- const driverSchema = await this.resolveDriverConfigSchema(deviceId, hubLocal);
659
- if (driverSchema) {
660
- for (const section of driverSchema.sections) {
661
- sections.push({
662
- id: section.id,
663
- title: section.title,
664
- tab: section.tab ?? "general",
665
- order: section.order ?? 1,
666
- fields: [...section.fields],
667
- ...section.description !== void 0 ? { description: section.description } : {},
668
- ...section.columns !== void 0 ? { columns: section.columns } : {}
669
- });
670
- }
671
- }
672
- return {
673
- sections,
674
- ...driverSchema?.tabs ? { tabs: [...driverSchema.tabs] } : {}
675
- };
676
- }
677
- /**
678
- * Lookup the native owner for `device-ops` on `deviceId` — the native-cap
679
- * registry (hub-local and remote) is keyed by numeric id.
680
- */
681
- resolveNativeDeviceOwner(deviceId) {
682
- const local = this.capabilityRegistry?.getNativeAddonId("device-ops", deviceId) ?? null;
683
- if (local) return { addonId: local, nodeId: this.ctx.kernel.localNodeId ?? "hub" };
684
- const remote = this.remoteNativeCaps.get(deviceId)?.get("device-ops") ?? null;
685
- return remote ? { addonId: remote.addonId, nodeId: remote.nodeId } : null;
686
- }
687
- /**
688
- * Aggregate `status` across every registered cap for a device.
689
- *
690
- * Walks the supplied cap list (or `CAP_NAMES_WITH_STATUS` when
691
- * omitted), looks up a native provider per cap via the capability
692
- * registry, calls `provider.getStatus({ deviceId })`, and validates
693
- * the return against the cap's own `status.schema`. Validation
694
- * failures log a warning and yield `null` for that cap so the
695
- * overall aggregate stays usable — a single misbehaving provider
696
- * must not blank out a device's entire status view.
697
- *
698
- * Returned shape is `Record<capName, unknown | null>`; the client-
699
- * side hook tightens this to `CapStatusTypeMap` via the generated
700
- * `cap-status-types.ts`.
701
- */
702
- async getDeviceStatusAggregate(input) {
703
- const capNames = input.caps ?? import_types2.CAP_NAMES_WITH_STATUS;
704
- const registry = this.capabilityRegistry;
705
- const out = {};
706
- if (!registry) {
707
- for (const name of capNames) out[name] = null;
708
- return out;
709
- }
710
- await Promise.all(capNames.map(async (capName) => {
711
- try {
712
- const def = registry.getDefinition(capName);
713
- if (!def?.status) {
714
- out[capName] = null;
715
- return;
716
- }
717
- const provider = registry.getNativeProvider(capName, input.deviceId);
718
- if (!provider || typeof provider.getStatus !== "function") {
719
- out[capName] = null;
720
- return;
721
- }
722
- const raw = await provider.getStatus({ deviceId: input.deviceId });
723
- if (raw == null) {
724
- out[capName] = null;
725
- return;
726
- }
727
- const parsed = def.status.schema.safeParse(raw);
728
- if (!parsed.success) {
729
- this.ctx.logger.warn("getDeviceStatusAggregate: provider returned invalid status, dropping", {
730
- tags: { deviceId: input.deviceId },
731
- meta: { capName, issues: parsed.error.issues.slice(0, 3) }
732
- });
733
- out[capName] = null;
734
- return;
735
- }
736
- out[capName] = parsed.data;
737
- } catch (err) {
738
- this.ctx.logger.warn("getDeviceStatusAggregate: provider threw, dropping", {
739
- tags: { deviceId: input.deviceId },
740
- meta: { capName, error: (0, import_types.errMsg)(err) }
741
- });
742
- out[capName] = null;
743
- }
744
- }));
745
- return out;
746
- }
747
- /**
748
- * Return the driver-specific device-settings contribution. Hub-local
749
- * devices call `getSettingsUISchema()` directly; forked-worker devices
750
- * go through the `device-ops.getSettingsSchema` cap method on the
751
- * numeric-id-keyed native registry.
752
- */
753
- async resolveDriverConfigSchema(deviceId, hubLocal) {
754
- if (hubLocal) {
755
- const schema = hubLocal.device.getSettingsUISchema();
756
- return schema.sections.length === 0 ? null : toWireShape(schema);
757
- }
758
- const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
759
- if (!ops) return null;
760
- try {
761
- const schema = await ops.getSettingsSchema({ deviceId });
762
- if (!schema) return null;
763
- const wire = schema;
764
- return wire.sections.length === 0 ? null : toWireShape(wire);
765
- } catch (err) {
766
- const msg = err instanceof Error ? err.message : String(err);
767
- this.ctx.logger.warn("cross-process getSettingsSchema failed", { tags: { deviceId }, meta: { error: msg } });
768
- return null;
769
- }
770
- }
771
- async updateDeviceField(input) {
772
- if (input.writerCapName === "device-manager") {
773
- const hubRegistry = this.ctx.kernel?.deviceRegistry;
774
- const found = hubRegistry ? resolveDeviceById(hubRegistry, input.deviceId) : null;
775
- if (found) {
776
- await found.device.applySettingsPatch({ [input.key]: input.value });
777
- return { success: true };
778
- }
779
- const ops = this.capabilityRegistry?.getNativeProvider("device-ops", input.deviceId);
780
- if (!ops) {
781
- throw new Error(`[device-manager] device "${input.deviceId}" not found (no hub-local entry, no device-ops native provider)`);
782
- }
783
- await ops.setConfig({ deviceId: input.deviceId, values: { [input.key]: input.value } });
784
- return { success: true };
785
- }
786
- const registry = this.capabilityRegistry;
787
- if (!registry) {
788
- throw new Error("[device-manager] updateDeviceField requires capability registry \u2014 unavailable on this node");
789
- }
790
- const def = registry.getDefinition(input.writerCapName);
791
- if (!def?.exposesDeviceSettings) {
792
- throw new Error(`[device-manager] cap "${input.writerCapName}" does not expose device settings`);
793
- }
794
- const provider = registry.getProviderByAddon(input.writerCapName, input.writerAddonId);
795
- if (!provider) {
796
- throw new Error(`[device-manager] provider "${input.writerAddonId}" not registered for cap "${input.writerCapName}"`);
797
- }
798
- await provider.applyDeviceSettingsPatch({
799
- deviceId: input.deviceId,
800
- patch: { [input.key]: input.value }
801
- });
802
- return { success: true };
803
- }
804
- /**
805
- * Batched counterpart of `updateDeviceField`. Groups changes by
806
- * `(writerCapName, writerAddonId)` so each contributor receives a
807
- * single `applyDeviceSettingsPatch` with all of its updates merged —
808
- * avoids N round-trips for simultaneous edits in the same save.
809
- *
810
- * Per-provider failures are captured in the `failures[]` output so the
811
- * admin UI can highlight which sections didn't persist; a failure on
812
- * one provider does NOT abort the others.
813
- */
814
- async updateDeviceFieldsBatch(input) {
815
- const groups = /* @__PURE__ */ new Map();
816
- for (const change of input.changes) {
817
- const key = `${change.writerCapName}::${change.writerAddonId}`;
818
- const existing = groups.get(key);
819
- if (existing) {
820
- existing.patch[change.key] = change.value;
821
- } else {
822
- groups.set(key, {
823
- writerCapName: change.writerCapName,
824
- writerAddonId: change.writerAddonId,
825
- patch: { [change.key]: change.value }
826
- });
827
- }
828
- }
829
- const failures = [];
830
- for (const group of groups.values()) {
831
- try {
832
- await this.applyGroupPatch(input.deviceId, group);
833
- } catch (err) {
834
- failures.push({
835
- writerCapName: group.writerCapName,
836
- writerAddonId: group.writerAddonId,
837
- error: err instanceof Error ? err.message : String(err)
838
- });
839
- }
840
- }
841
- return { success: true, failures };
842
- }
843
- /** Apply a single grouped patch to the appropriate provider. Mirrors
844
- * `updateDeviceField` routing (special-case device-manager, else
845
- * registry lookup). Used by `updateDeviceFieldsBatch`. */
846
- async applyGroupPatch(deviceId, group) {
847
- if (group.writerCapName === "device-manager") {
848
- const hubRegistry = this.ctx.kernel?.deviceRegistry;
849
- const found = hubRegistry ? resolveDeviceById(hubRegistry, deviceId) : null;
850
- if (found) {
851
- await found.device.applySettingsPatch(group.patch);
852
- return;
853
- }
854
- const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
855
- if (!ops) {
856
- throw new Error(`[device-manager] device "${deviceId}" not found (no hub-local entry, no device-ops native provider)`);
857
- }
858
- await ops.setConfig({ deviceId, values: group.patch });
859
- return;
860
- }
861
- const registry = this.capabilityRegistry;
862
- if (!registry) throw new Error("[device-manager] capability registry unavailable");
863
- const def = registry.getDefinition(group.writerCapName);
864
- if (!def?.exposesDeviceSettings) {
865
- throw new Error(`[device-manager] cap "${group.writerCapName}" does not expose device settings`);
866
- }
867
- const provider = registry.getProviderByAddon(group.writerCapName, group.writerAddonId);
868
- if (!provider) {
869
- throw new Error(`[device-manager] provider "${group.writerAddonId}" not registered for cap "${group.writerCapName}"`);
870
- }
871
- await provider.applyDeviceSettingsPatch({ deviceId, patch: group.patch });
872
- }
873
- async listWrappersForCap(input) {
874
- return [...this.capabilityRegistry?.getWrappersForCap(input.capName) ?? []];
875
- }
876
- async listBindableCapsForDeviceType(input) {
877
- const registry = this.capabilityRegistry;
878
- if (!registry) return [];
879
- const capNames = registry.listDeviceScopedCapsForType(input.deviceType);
880
- return capNames.map((capName) => ({
881
- capName,
882
- wrappers: [...registry.getWrappersForCap(capName)]
883
- }));
884
- }
885
- async setWrapperActive(input) {
886
- const storeKey = String(input.deviceId);
887
- const store = await this.readBindingsStore();
888
- const perDevice = { ...store.deviceBindings[storeKey] ?? {} };
889
- if (input.active) {
890
- perDevice[input.capName] = { wrapperAddonId: input.wrapperAddonId };
891
- } else {
892
- perDevice[input.capName] = { wrapperAddonId: null };
893
- }
894
- const nextDeviceBindings = Object.keys(perDevice).length > 0 ? { ...store.deviceBindings, [storeKey]: perDevice } : (() => {
895
- const { [storeKey]: _drop, ...rest } = store.deviceBindings;
896
- return rest;
897
- })();
898
- await this.writeBindingsStore({ deviceBindings: nextDeviceBindings });
899
- this.ctx.eventBus.emit({
900
- id: (0, import_node_crypto.randomUUID)(),
901
- timestamp: /* @__PURE__ */ new Date(),
902
- source: { type: "addon", id: this.ctx.id },
903
- category: import_types.EventCategory.DeviceBindingsChanged,
904
- data: {
905
- deviceId: input.deviceId,
906
- capName: input.capName,
907
- reason: input.active ? "wrapper-activated" : "wrapper-deactivated",
908
- addonId: input.wrapperAddonId,
909
- nodeId: this.resolveWrapperNodeId(input.wrapperAddonId)
910
- }
911
- });
912
- }
913
- async onInitialize() {
914
- const settings = this.ctx.settings;
915
- if (!settings) {
916
- this.ctx.logger.warn("ctx.settings not available \u2014 device persistence unavailable");
917
- return;
918
- }
919
- const registry = this.ctx.kernel.deviceRegistry ?? null;
920
- if (!registry) {
921
- this.ctx.logger.warn("device-registry not available \u2014 live operations will use persisted data only");
922
- }
923
- const localNodeId = this.ctx.kernel.localNodeId ?? "hub";
924
- this.ctx.eventBus.subscribe(
925
- { category: import_types.EventCategory.DeviceBindingsChanged },
926
- (event) => {
927
- const { deviceId, capName, reason, addonId, nodeId } = event.data;
928
- if (nodeId === localNodeId) return;
929
- if (reason === "native-registered") {
930
- let perDevice = this.remoteNativeCaps.get(deviceId);
931
- if (!perDevice) {
932
- perDevice = /* @__PURE__ */ new Map();
933
- this.remoteNativeCaps.set(deviceId, perDevice);
934
- }
935
- perDevice.set(capName, { addonId, nodeId });
936
- } else if (reason === "native-unregistered") {
937
- const perDevice = this.remoteNativeCaps.get(deviceId);
938
- if (!perDevice) return;
939
- perDevice.delete(capName);
940
- if (perDevice.size === 0) this.remoteNativeCaps.delete(deviceId);
941
- }
942
- }
943
- );
944
- const cluster = this.ctx.kernel.cluster;
945
- if (cluster) {
946
- cluster.broker.localBus.on("$node.disconnected", (payload) => {
947
- const gone = payload.node.id;
948
- const emptyDevices = [];
949
- for (const [deviceId, perDevice] of this.remoteNativeCaps) {
950
- const toDelete = [];
951
- for (const [capName, entry] of perDevice) {
952
- if (entry.nodeId === gone) toDelete.push(capName);
953
- }
954
- for (const capName of toDelete) perDevice.delete(capName);
955
- if (perDevice.size === 0) emptyDevices.push(deviceId);
956
- }
957
- for (const deviceId of emptyDevices) this.remoteNativeCaps.delete(deviceId);
958
- });
959
- }
960
- const requireDeviceOps = (deviceId) => {
961
- const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
962
- if (!ops) {
963
- throw new Error(`[device-manager] device-ops native provider not found for '${deviceId}'`);
964
- }
965
- return ops;
966
- };
967
- const readStore = async () => {
968
- return await settings.readAddonStore();
969
- };
970
- const readIndex = async () => {
971
- const store = await readStore();
972
- return store.deviceIndex ?? {};
973
- };
974
- const readMeta = async () => {
975
- const store = await readStore();
976
- return store.deviceMeta ?? {};
977
- };
978
- const readMetadataMap = async () => {
979
- const store = await readStore();
980
- return store.deviceMetadata ?? {};
981
- };
982
- let metaWriteChain = Promise.resolve();
983
- const withMetaWriteLock = async (fn) => {
984
- const previous = metaWriteChain;
985
- let release = () => {
986
- };
987
- const next = new Promise((resolve) => {
988
- release = resolve;
989
- });
990
- metaWriteChain = next;
991
- try {
992
- await previous.catch(() => {
993
- });
994
- return await fn();
995
- } finally {
996
- release();
997
- }
998
- };
999
- const resolvePersistedById = async (deviceId) => {
1000
- const meta = await readMeta();
1001
- for (const [key, m] of Object.entries(meta)) {
1002
- if (m.id === deviceId) {
1003
- const sep = key.indexOf(":");
1004
- if (sep < 0) continue;
1005
- return { addonId: key.slice(0, sep), stableId: key.slice(sep + 1), meta: m };
1006
- }
1007
- }
1008
- return null;
1009
- };
1010
- const idToAddonId = /* @__PURE__ */ new Map();
1011
- {
1012
- const meta = await readMeta();
1013
- for (const [key, m] of Object.entries(meta)) {
1014
- const sep = key.indexOf(":");
1015
- if (sep < 0) continue;
1016
- idToAddonId.set(m.id, key.slice(0, sep));
1017
- }
1018
- }
1019
- if (cluster) {
1020
- cluster.broker.localBus.on("$node.connected", (payload) => {
1021
- const connectedNodeId = payload.node.id;
1022
- const lastSlash = connectedNodeId.lastIndexOf("/");
1023
- if (lastSlash < 0) return;
1024
- const connectedAddonId = connectedNodeId.slice(lastSlash + 1);
1025
- if (connectedAddonId.length === 0) return;
1026
- for (const [deviceId, ownerAddonId] of idToAddonId) {
1027
- if (ownerAddonId !== connectedAddonId) continue;
1028
- if (this.capabilityRegistry?.getNativeAddonId("device-ops", deviceId)) continue;
1029
- let perDevice = this.remoteNativeCaps.get(deviceId);
1030
- if (!perDevice) {
1031
- perDevice = /* @__PURE__ */ new Map();
1032
- this.remoteNativeCaps.set(deviceId, perDevice);
1033
- }
1034
- if (!perDevice.has("device-ops")) {
1035
- perDevice.set("device-ops", { addonId: connectedAddonId, nodeId: connectedNodeId });
1036
- }
1037
- }
1038
- setTimeout(() => {
1039
- this.discoverWorkerNativeCaps(connectedNodeId, connectedAddonId).catch((err) => {
1040
- this.ctx.logger.warn("worker native-cap discovery failed", {
1041
- meta: { nodeId: connectedNodeId, addonId: connectedAddonId, error: (0, import_types.errMsg)(err) }
1042
- });
1043
- });
1044
- }, 500);
1045
- });
1046
- }
1047
- const allocateNextDeviceId = async () => {
1048
- const store = await readStore();
1049
- const current = store.nextDeviceId ?? 1;
1050
- await settings.writeAddonStore({ nextDeviceId: current + 1 });
1051
- return current;
1052
- };
1053
- const provider = {
1054
- /** Sync ownership lookup backing persistence fallbacks (e.g. remove()
1055
- * when the owning worker is offline). Ownership is keyed by numeric
1056
- * deviceId → owning addonId as recorded in the persisted meta. NOT
1057
- * a native-cap lookup: an addon can own a device without registering
1058
- * every possible cap natively (e.g. RtspCamera without snapshotUrl
1059
- * doesn't register the snapshot cap). Use
1060
- * `resolveNativeCapOwnerSync` for cap-resolution paths.
1061
- */
1062
- resolveDeviceOwnerSync: (deviceId) => {
1063
- return idToAddonId.get(deviceId) ?? null;
1064
- },
1065
- /** Sync lookup for the addon that registered a native provider for
1066
- * `(capName, deviceId)`. Backs `CapabilityRegistry`'s native fallback
1067
- * so the hub only synthesizes a cross-process proxy when the cap is
1068
- * actually published — never on speculative device ownership.
1069
- *
1070
- * Consults hub-local registrations first (in-process natives),
1071
- * then the `remoteNativeCaps` map populated from
1072
- * `DeviceBindingsChanged` events emitted by forked-worker
1073
- * `registerNativeCap` calls. Both are generic: any addon that hosts
1074
- * devices and registers caps via the standard context API shows up
1075
- * here without per-addon branching.
1076
- */
1077
- resolveNativeCapOwnerSync: (capName, deviceId) => {
1078
- const localAddonId = this.capabilityRegistry?.getNativeAddonId(capName, deviceId) ?? null;
1079
- if (localAddonId) {
1080
- return { addonId: localAddonId, nodeId: this.ctx.kernel.localNodeId ?? "hub" };
1081
- }
1082
- const remote = this.remoteNativeCaps.get(deviceId)?.get(capName) ?? null;
1083
- if (remote) return { addonId: remote.addonId, nodeId: remote.nodeId };
1084
- return null;
1085
- },
1086
- // ── Persistence ────────────────────────────────────────────────────────
1087
- /** Idempotent numeric-id reservation. Callers invoke this before
1088
- * constructing the owning `IDevice` so `DeviceContext.id` is bound
1089
- * at construction time. A repeat call for the same `(addonId,
1090
- * stableId)` returns the already-persisted id — same physical
1091
- * device reconnecting after a driver restart keeps its original
1092
- * number. Fresh pairs burn one slot from the monotonic
1093
- * `nextDeviceId` counter and seed a meta placeholder so the
1094
- * `deviceMeta` → `id` invariant holds even before
1095
- * `registerDevice` completes. */
1096
- allocateDeviceId: async (input) => {
1097
- const { addonId, stableId } = input;
1098
- const key = deviceKey(addonId, stableId);
1099
- return await withMetaWriteLock(async () => {
1100
- const meta = await readMeta();
1101
- const existing = meta[key];
1102
- if (existing) return { id: existing.id };
1103
- const id = await allocateNextDeviceId();
1104
- await settings.writeAddonStore({
1105
- deviceMeta: {
1106
- ...meta,
1107
- [key]: {
1108
- type: "generic",
1109
- name: stableId,
1110
- location: null,
1111
- disabled: false,
1112
- parentDeviceId: null,
1113
- id
1114
- }
1115
- }
1116
- });
1117
- return { id };
1118
- });
1119
- },
1120
- registerDevice: async (input) => {
1121
- const { addonId, stableId, id, type, name, parentDeviceId, features, config } = input;
1122
- const key = deviceKey(addonId, stableId);
1123
- const featuresArr = Array.isArray(features) ? [...features] : [];
1124
- const { isFirstRegistration } = await withMetaWriteLock(async () => {
1125
- const index = await readIndex();
1126
- const existing = index[addonId] ?? [];
1127
- const wasInIndex = existing.includes(stableId);
1128
- if (!wasInIndex) {
1129
- await settings.writeAddonStore({
1130
- deviceIndex: { ...index, [addonId]: [...existing, stableId] }
1131
- });
1132
- }
1133
- const meta = await readMeta();
1134
- const existingMeta = meta[key];
1135
- const isFirst = !existingMeta || !wasInIndex;
1136
- await settings.writeAddonStore({
1137
- deviceMeta: {
1138
- ...meta,
1139
- [key]: {
1140
- type,
1141
- // Prefer the persisted name (set by `setName` pre-construct)
1142
- // over the construction-time fallback. Only when the meta
1143
- // row literally still carries `name === stableId` (the
1144
- // placeholder seeded by `allocateDeviceId`) do we fall
1145
- // back to the action arg.
1146
- name: existingMeta && existingMeta.name !== stableId ? existingMeta.name : name,
1147
- location: existingMeta?.location ?? null,
1148
- disabled: existingMeta?.disabled ?? false,
1149
- parentDeviceId,
1150
- id,
1151
- features: featuresArr
1152
- }
1153
- }
1154
- });
1155
- return { isFirstRegistration: isFirst };
1156
- });
1157
- if (Object.keys(config).length > 0) {
1158
- await settings.writeDeviceStore(id, config);
1159
- }
1160
- idToAddonId.set(id, addonId);
1161
- if (isFirstRegistration) {
1162
- this.ctx.eventBus.emit({
1163
- id: (0, import_node_crypto.randomUUID)(),
1164
- timestamp: /* @__PURE__ */ new Date(),
1165
- source: { type: "device", id },
1166
- category: import_types.EventCategory.DeviceRegistered,
1167
- data: {
1168
- deviceId: id,
1169
- name: name.length > 0 ? name : stableId,
1170
- providerId: addonId,
1171
- parentDeviceId: parentDeviceId ?? null
1172
- }
1173
- });
1174
- } else {
1175
- this.ctx.eventBus.emit({
1176
- id: (0, import_node_crypto.randomUUID)(),
1177
- timestamp: /* @__PURE__ */ new Date(),
1178
- source: { type: "device", id },
1179
- category: import_types.EventCategory.DeviceMetaChanged,
1180
- data: {
1181
- deviceId: id,
1182
- name: name.length > 0 ? name : stableId,
1183
- providerId: addonId,
1184
- parentDeviceId: parentDeviceId ?? null,
1185
- features: featuresArr
1186
- }
1187
- });
1188
- }
1189
- },
1190
- removeDevice: async (input) => {
1191
- const { deviceId } = input;
1192
- const persisted = await resolvePersistedById(deviceId);
1193
- if (!persisted) {
1194
- return;
1195
- }
1196
- const { addonId, stableId, meta: persistedMeta } = persisted;
1197
- const key = deviceKey(addonId, stableId);
1198
- const deviceName = persistedMeta.name;
1199
- await withMetaWriteLock(async () => {
1200
- const index = await readIndex();
1201
- const remaining = (index[addonId] ?? []).filter((sid) => sid !== stableId);
1202
- const updatedIndex = remaining.length > 0 ? { ...index, [addonId]: remaining } : (() => {
1203
- const { [addonId]: _removed, ...rest } = index;
1204
- return rest;
1205
- })();
1206
- await settings.writeAddonStore({ deviceIndex: updatedIndex });
1207
- const meta = await readMeta();
1208
- const { [key]: _removedMeta, ...restMeta } = meta;
1209
- await settings.writeAddonStore({ deviceMeta: restMeta });
1210
- const map = await readMetadataMap();
1211
- if (key in map) {
1212
- const { [key]: _removedMetadata, ...restMap } = map;
1213
- await settings.writeAddonStore({ deviceMetadata: restMap });
1214
- }
1215
- });
1216
- await settings.clearDeviceStore(deviceId);
1217
- const bindingsStore = await this.readBindingsStore();
1218
- const bindingKey = String(deviceId);
1219
- if (bindingsStore.deviceBindings[bindingKey]) {
1220
- const { [bindingKey]: _removedBindings, ...restBindings } = bindingsStore.deviceBindings;
1221
- await this.writeBindingsStore({ deviceBindings: restBindings });
1222
- }
1223
- this.remoteNativeCaps.delete(deviceId);
1224
- this.capabilityRegistry?.unregisterAllNativeForDevice(deviceId);
1225
- idToAddonId.delete(deviceId);
1226
- this.ctx.logger.info("removed device", { tags: { deviceId, deviceName: deviceName.length > 0 ? deviceName : stableId } });
1227
- this.ctx.eventBus.emit({
1228
- id: (0, import_node_crypto.randomUUID)(),
1229
- timestamp: /* @__PURE__ */ new Date(),
1230
- source: { type: "device", id: deviceId },
1231
- category: import_types.EventCategory.DeviceUnregistered,
1232
- data: {
1233
- deviceId,
1234
- providerId: addonId,
1235
- // Carry parentDeviceId so listeners can filter on "is
1236
- // this MY child?" without consulting an in-memory map
1237
- // they had to keep in sync. By the time this event
1238
- // fires the meta row is already gone — we read it from
1239
- // the resolved snapshot above.
1240
- parentDeviceId: persistedMeta.parentDeviceId ?? null
1241
- }
1242
- });
1243
- },
1244
- persistConfig: async (input) => {
1245
- const { deviceId, data } = input;
1246
- const persisted = await resolvePersistedById(deviceId);
1247
- if (!persisted) throw new Error(`[device-manager] persistConfig: unknown device id=${deviceId}`);
1248
- await settings.writeDeviceStore(deviceId, data);
1249
- },
1250
- loadConfig: async (input) => {
1251
- const { deviceId } = input;
1252
- const persisted = await resolvePersistedById(deviceId);
1253
- if (!persisted) return {};
1254
- return settings.readDeviceStore(deviceId);
1255
- },
1256
- /**
1257
- * Load the operator-organisational meta surface for one device
1258
- * (`name` / `location` / `disabled` / `type` / `parentDeviceId`
1259
- * / `addonId` + `id` / `stableId`). Used by the kernel proxy's
1260
- * device-context factory to populate `ctx.deviceMeta` before
1261
- * the device class constructor runs. Returns `null` when no
1262
- * persisted row exists for the id.
1263
- *
1264
- * Reads default `location` to `null` and `disabled` to `false`
1265
- * for legacy rows that predate the field — production code
1266
- * relies on the IDevice type contract that both are present.
1267
- */
1268
- loadMeta: async (input) => {
1269
- const { deviceId } = input;
1270
- const persisted = await resolvePersistedById(deviceId);
1271
- if (!persisted) return null;
1272
- const { addonId, stableId, meta: m } = persisted;
1273
- const key = deviceKey(addonId, stableId);
1274
- const map = await readMetadataMap();
1275
- const metadata = map[key] ?? null;
1276
- return {
1277
- id: m.id,
1278
- stableId,
1279
- addonId,
1280
- type: m.type,
1281
- name: m.name,
1282
- location: m.location ?? null,
1283
- disabled: m.disabled ?? false,
1284
- parentDeviceId: m.parentDeviceId,
1285
- metadata
1286
- };
1287
- },
1288
- /**
1289
- * Update the operator-edited display name. Writes the meta
1290
- * row, emits a `DeviceMetaChanged` event so live consumers
1291
- * (UI device list, alert center) see the rename without
1292
- * polling. The live `IDevice.name` mirror is updated by the
1293
- * kernel proxy on its side (`device-cap-proxy.ts`).
1294
- */
1295
- setName: async (input) => {
1296
- const { deviceId, name } = input;
1297
- await withMetaWriteLock(async () => {
1298
- const persisted = await resolvePersistedById(deviceId);
1299
- if (!persisted) throw new Error(`[device-manager] setName: unknown device id=${deviceId}`);
1300
- const { addonId, stableId, meta: m } = persisted;
1301
- const key = deviceKey(addonId, stableId);
1302
- const allMeta = await readMeta();
1303
- await settings.writeAddonStore({
1304
- deviceMeta: { ...allMeta, [key]: { ...m, name } }
1305
- });
1306
- });
1307
- this.ctx.eventBus.emit({
1308
- id: (0, import_node_crypto.randomUUID)(),
1309
- timestamp: /* @__PURE__ */ new Date(),
1310
- source: { type: "device", id: deviceId },
1311
- category: import_types.EventCategory.DeviceMetaChanged,
1312
- data: { deviceId, field: "name", value: name }
1313
- });
1314
- },
1315
- /**
1316
- * Update the operator-organisational location label. `null`
1317
- * clears it. Mirrors the same persist-then-emit shape as
1318
- * `setName`; consumers subscribe to `DeviceMetaChanged` and
1319
- * filter on `field: 'location'`.
1320
- */
1321
- setLocation: async (input) => {
1322
- const { deviceId, location } = input;
1323
- await withMetaWriteLock(async () => {
1324
- const persisted = await resolvePersistedById(deviceId);
1325
- if (!persisted) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
1326
- const { addonId, stableId, meta: m } = persisted;
1327
- const key = deviceKey(addonId, stableId);
1328
- const allMeta = await readMeta();
1329
- await settings.writeAddonStore({
1330
- deviceMeta: { ...allMeta, [key]: { ...m, location } }
1331
- });
1332
- });
1333
- this.ctx.eventBus.emit({
1334
- id: (0, import_node_crypto.randomUUID)(),
1335
- timestamp: /* @__PURE__ */ new Date(),
1336
- source: { type: "device", id: deviceId },
1337
- category: import_types.EventCategory.DeviceMetaChanged,
1338
- data: { deviceId, field: "location", value: location }
1339
- });
1340
- },
1341
- /**
1342
- * Patch the device's hardware-identity metadata blob. Shallow
1343
- * merge — `null` removes a key, anything else overwrites.
1344
- * Drivers populate factual fields on first probe; operators
1345
- * augment via the Device Info tab. Idempotent: a no-op patch
1346
- * (every key already present with the same value) doesn't emit
1347
- * the meta-changed event.
1348
- */
1349
- setMetadata: async (input) => {
1350
- const { deviceId, patch } = input;
1351
- const result = await withMetaWriteLock(async () => {
1352
- const persisted = await resolvePersistedById(deviceId);
1353
- if (!persisted) throw new Error(`[device-manager] setMetadata: unknown device id=${deviceId}`);
1354
- const { addonId, stableId } = persisted;
1355
- const key = deviceKey(addonId, stableId);
1356
- const map = await readMetadataMap();
1357
- const current = map[key] ?? {};
1358
- const next = { ...current };
1359
- let changed = false;
1360
- for (const [k, v] of Object.entries(patch)) {
1361
- if (v === null) {
1362
- if (k in next) {
1363
- delete next[k];
1364
- changed = true;
1365
- }
1366
- } else if (next[k] !== v) {
1367
- next[k] = v;
1368
- changed = true;
1369
- }
1370
- }
1371
- if (!changed) return { changed: false };
1372
- const hasFields = Object.keys(next).length > 0;
1373
- const updatedMap = { ...map };
1374
- if (hasFields) {
1375
- updatedMap[key] = next;
1376
- } else {
1377
- delete updatedMap[key];
1378
- }
1379
- await settings.writeAddonStore({ deviceMetadata: updatedMap });
1380
- return { changed: true, finalMeta: hasFields ? next : null };
1381
- });
1382
- if (!result.changed) return;
1383
- this.ctx.eventBus.emit({
1384
- id: (0, import_node_crypto.randomUUID)(),
1385
- timestamp: /* @__PURE__ */ new Date(),
1386
- source: { type: "device", id: deviceId },
1387
- category: import_types.EventCategory.DeviceMetaChanged,
1388
- data: { deviceId, field: "metadata", value: result.finalMeta }
1389
- });
1390
- },
1391
- /**
1392
- * Soft-disable the device. Persisted on the meta row;
1393
- * lifecycle gating is the driver's responsibility (BaseDevice
1394
- * exposes `this.disabled` for the driver to consult at the top
1395
- * of its lifecycle methods).
1396
- */
1397
- setDisabled: async (input) => {
1398
- const { deviceId, disabled } = input;
1399
- await withMetaWriteLock(async () => {
1400
- const persisted = await resolvePersistedById(deviceId);
1401
- if (!persisted) throw new Error(`[device-manager] setDisabled: unknown device id=${deviceId}`);
1402
- const { addonId, stableId, meta: m } = persisted;
1403
- const key = deviceKey(addonId, stableId);
1404
- const allMeta = await readMeta();
1405
- await settings.writeAddonStore({
1406
- deviceMeta: { ...allMeta, [key]: { ...m, disabled } }
1407
- });
1408
- });
1409
- this.ctx.eventBus.emit({
1410
- id: (0, import_node_crypto.randomUUID)(),
1411
- timestamp: /* @__PURE__ */ new Date(),
1412
- source: { type: "device", id: deviceId },
1413
- category: import_types.EventCategory.DeviceMetaChanged,
1414
- data: { deviceId, field: "disabled", value: disabled }
1415
- });
1416
- },
1417
- loadRuntimeState: async (input) => {
1418
- const { deviceId } = input;
1419
- const persisted = await resolvePersistedById(deviceId);
1420
- if (!persisted) return {};
1421
- const data = await settings.readDeviceRuntimeState(deviceId);
1422
- this.seedMirror(deviceId, data);
1423
- return data;
1424
- },
1425
- /**
1426
- * Union of (1) operator-curated location registry and (2) labels
1427
- * currently in use on persisted devices. Case-insensitive
1428
- * dedupe (preserves the first-seen casing). Sorted
1429
- * case-insensitively for stable UI. Drives the Device Info
1430
- * location autocomplete.
1431
- */
1432
- listLocations: async () => {
1433
- const store = await settings.readAddonStore();
1434
- const meta = store.deviceMeta ?? {};
1435
- const registry2 = store.locations ?? [];
1436
- const seen = /* @__PURE__ */ new Map();
1437
- const consider = (raw) => {
1438
- if (typeof raw !== "string") return;
1439
- const trimmed = raw.trim();
1440
- if (trimmed.length === 0) return;
1441
- const key = trimmed.toLowerCase();
1442
- if (!seen.has(key)) seen.set(key, trimmed);
1443
- };
1444
- for (const label of registry2) consider(label);
1445
- for (const m of Object.values(meta)) consider(m.location);
1446
- return [...seen.values()].sort(
1447
- (a, b) => a.localeCompare(b, void 0, { sensitivity: "base" })
1448
- );
1449
- },
1450
- /**
1451
- * Add a label to the curated location registry. Idempotent:
1452
- * existing entries (case-insensitive match) are silently kept.
1453
- * Empty / whitespace-only inputs throw — operators must supply a
1454
- * meaningful label.
1455
- */
1456
- addLocation: async (input) => {
1457
- const trimmed = input.name.trim();
1458
- if (trimmed.length === 0) {
1459
- throw new Error("[device-manager] addLocation: name must be non-empty");
1460
- }
1461
- const store = await settings.readAddonStore();
1462
- const current = store.locations ?? [];
1463
- if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) {
1464
- return;
1465
- }
1466
- await settings.writeAddonStore({ locations: [...current, trimmed] });
1467
- },
1468
- /**
1469
- * Remove a label from the curated registry. Match is
1470
- * case-insensitive. Devices that still reference this label keep
1471
- * their `meta.location` value (the registry is a suggestion
1472
- * list, not a foreign key) — pass `cascade: true` to also clear
1473
- * `setLocation` on every device that referenced this exact
1474
- * label. Cascade only matches case-insensitively + trimmed, same
1475
- * as the registry equality check.
1476
- */
1477
- removeLocation: async (input) => {
1478
- const trimmed = input.name.trim();
1479
- if (trimmed.length === 0) return;
1480
- const store = await settings.readAddonStore();
1481
- const current = store.locations ?? [];
1482
- const remaining = current.filter((l) => l.toLowerCase() !== trimmed.toLowerCase());
1483
- if (remaining.length !== current.length) {
1484
- await settings.writeAddonStore({ locations: remaining });
1485
- }
1486
- if (input.cascade !== true) return;
1487
- const meta = store.deviceMeta ?? {};
1488
- const updates = { ...meta };
1489
- const cleared = [];
1490
- for (const [key, m] of Object.entries(meta)) {
1491
- if (typeof m.location !== "string") continue;
1492
- if (m.location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
1493
- updates[key] = { ...m, location: null };
1494
- cleared.push(m.id);
1495
- }
1496
- if (cleared.length === 0) return;
1497
- await settings.writeAddonStore({ deviceMeta: updates });
1498
- for (const deviceId of cleared) {
1499
- this.ctx.eventBus.emit({
1500
- id: (0, import_node_crypto.randomUUID)(),
1501
- timestamp: /* @__PURE__ */ new Date(),
1502
- source: { type: "device", id: deviceId },
1503
- category: import_types.EventCategory.DeviceMetaChanged,
1504
- data: { deviceId, field: "location", value: null }
1505
- });
1506
- }
1507
- },
1508
- listPersistedByAddon: async (input) => {
1509
- const { addonId } = input;
1510
- const [index, meta] = await Promise.all([readIndex(), readMeta()]);
1511
- const stableIds = index[addonId] ?? [];
1512
- return stableIds.map((stableId) => {
1513
- const m = meta[deviceKey(addonId, stableId)];
1514
- return {
1515
- id: m.id,
1516
- stableId,
1517
- type: m.type,
1518
- name: m.name,
1519
- location: m.location ?? null,
1520
- disabled: m.disabled ?? false,
1521
- parentDeviceId: m.parentDeviceId
1522
- };
1523
- });
1524
- },
1525
- // ── Live queries — serve from live registry when available ────────────
1526
- listAll: async (input) => {
1527
- const { addonId } = input;
1528
- const results = [];
1529
- const seen = /* @__PURE__ */ new Set();
1530
- const meta = await readMeta();
1531
- const metadataMap = await readMetadataMap();
1532
- if (registry) {
1533
- const liveEntries = addonId ? registry.getAllForAddon(addonId).map((device) => ({ addonId, device })) : registry.getAllWithAddonId();
1534
- for (const { addonId: aid, device } of liveEntries) {
1535
- const key = deviceKey(aid, device.stableId);
1536
- const metadata = metadataMap[key] ?? null;
1537
- const metaRow = meta[key] ?? null;
1538
- results.push(toDeviceInfo(aid, device, metadata, metaRow));
1539
- seen.add(key);
1540
- }
1541
- }
1542
- const index = await readIndex();
1543
- const targetAddons = addonId ? [addonId] : Object.keys(index);
1544
- for (const aid of targetAddons) {
1545
- for (const stableId of index[aid] ?? []) {
1546
- const key = deviceKey(aid, stableId);
1547
- if (seen.has(key)) continue;
1548
- const m = meta[key];
1549
- const persistedType = m.type;
1550
- const persistedConfig = await settings.readDeviceStore(m.id);
1551
- const metadata = metadataMap[key] ?? null;
1552
- results.push({
1553
- id: m.id,
1554
- stableId,
1555
- addonId: aid,
1556
- type: persistedType,
1557
- name: m?.name ?? stableId,
1558
- location: m?.location ?? null,
1559
- disabled: m?.disabled ?? false,
1560
- parentDeviceId: m?.parentDeviceId ?? null,
1561
- // role is not persisted to disk — only set on the live
1562
- // IDevice (`BaseDevice.role`) by accessory subclasses. The
1563
- // forked-worker fallback path can't read it, so emit null;
1564
- // accessories typically run in the same process as their
1565
- // parent provider, so the live path covers them in practice.
1566
- role: null,
1567
- // registry===null was the legacy "offline view" signal; keep it
1568
- // for that case so existing callers see online=false. When a
1569
- // registry is present and the device lives elsewhere (forked
1570
- // worker), default to online=true — persisted state implies it
1571
- // was successfully registered by its owning process.
1572
- online: registry !== null,
1573
- features: persistedFeatures(m?.features),
1574
- // Live IDevice isn't reachable from the hub, so infer
1575
- // isCamera from the persisted DeviceType rather than the
1576
- // method-presence check `toDeviceInfo` uses. Without this
1577
- // forked-worker cameras looked non-camera to the stream-broker
1578
- // and never got their RTSP restream wired up.
1579
- isCamera: persistedType === import_types.DeviceType.Camera,
1580
- config: persistedConfig ?? {},
1581
- metadata
1582
- });
1583
- }
1584
- }
1585
- return results;
1586
- },
1587
- getDevice: async (input) => {
1588
- const { deviceId } = input;
1589
- if (registry) {
1590
- const found = resolveDeviceById(registry, deviceId);
1591
- if (found) {
1592
- const key2 = deviceKey(found.addonId, found.device.stableId);
1593
- const [map2, metaMap] = await Promise.all([readMetadataMap(), readMeta()]);
1594
- const metadata2 = map2[key2] ?? null;
1595
- const metaRow = metaMap[key2] ?? null;
1596
- return toDeviceInfo(found.addonId, found.device, metadata2, metaRow);
1597
- }
1598
- }
1599
- const persisted = await resolvePersistedById(deviceId);
1600
- if (!persisted) return null;
1601
- const { addonId: aid, stableId, meta: m } = persisted;
1602
- const persistedConfig = await settings.readDeviceStore(m.id);
1603
- const key = deviceKey(aid, stableId);
1604
- const map = await readMetadataMap();
1605
- const metadata = map[key] ?? null;
1606
- return {
1607
- id: deviceId,
1608
- stableId,
1609
- addonId: aid,
1610
- type: m.type,
1611
- name: m.name,
1612
- location: m.location ?? null,
1613
- disabled: m.disabled ?? false,
1614
- parentDeviceId: m.parentDeviceId,
1615
- role: null,
1616
- online: true,
1617
- features: persistedFeatures(m.features),
1618
- isCamera: false,
1619
- config: persistedConfig ?? {},
1620
- metadata
1621
- };
1622
- },
1623
- getChildren: async (input) => {
1624
- const { parentDeviceId } = input;
1625
- let ownerAddonId = null;
1626
- if (registry) {
1627
- const liveParent = registry.getById(parentDeviceId);
1628
- if (liveParent) {
1629
- ownerAddonId = registry.getAddonId(parentDeviceId);
1630
- }
1631
- }
1632
- if (!ownerAddonId) {
1633
- const persisted = await resolvePersistedById(parentDeviceId);
1634
- if (!persisted) return [];
1635
- ownerAddonId = persisted.addonId;
1636
- }
1637
- const results = [];
1638
- const seen = /* @__PURE__ */ new Set();
1639
- const [index, meta, metadataMap] = await Promise.all([readIndex(), readMeta(), readMetadataMap()]);
1640
- if (registry) {
1641
- const liveChildren = registry.getChildren(parentDeviceId);
1642
- for (const device of liveChildren) {
1643
- const key = deviceKey(ownerAddonId, device.stableId);
1644
- const metadata = metadataMap[key] ?? null;
1645
- const metaRow = meta[key] ?? null;
1646
- results.push(toDeviceInfo(ownerAddonId, device, metadata, metaRow));
1647
- seen.add(key);
1648
- }
1649
- }
1650
- const stableIds = index[ownerAddonId] ?? [];
1651
- const persistedChildren = stableIds.filter(
1652
- (sid) => meta[deviceKey(ownerAddonId, sid)]?.parentDeviceId === parentDeviceId
1653
- );
1654
- for (const childStableId of persistedChildren) {
1655
- const key = deviceKey(ownerAddonId, childStableId);
1656
- if (seen.has(key)) continue;
1657
- const m = meta[key];
1658
- const persistedConfig = await settings.readDeviceStore(m.id);
1659
- const metadata = metadataMap[key] ?? null;
1660
- results.push({
1661
- id: m.id,
1662
- stableId: childStableId,
1663
- addonId: ownerAddonId,
1664
- type: m.type,
1665
- name: m.name,
1666
- location: m.location ?? null,
1667
- disabled: m.disabled ?? false,
1668
- parentDeviceId,
1669
- role: null,
1670
- online: registry !== null,
1671
- features: persistedFeatures(m.features),
1672
- isCamera: false,
1673
- config: persistedConfig ?? {},
1674
- metadata
1675
- });
1676
- }
1677
- return results;
1678
- },
1679
- // ── Live runtime methods ──────────────────────────────────────────────
1680
- getStreamSources: async (input) => {
1681
- const { deviceId } = input;
1682
- if (registry) {
1683
- const found = resolveDeviceById(registry, deviceId);
1684
- if (found) {
1685
- if (!isCameraDevice(found.device)) return [];
1686
- const sources2 = await found.device.getStreamSources();
1687
- return sources2.map((s) => ({
1688
- id: s.id,
1689
- label: s.label,
1690
- protocol: s.protocol,
1691
- url: s.url,
1692
- resolution: s.resolution,
1693
- fps: s.fps,
1694
- bitrate: s.bitrate,
1695
- codec: s.codec,
1696
- profileHint: s.profileHint
1697
- }));
1698
- }
1699
- }
1700
- const persisted = await resolvePersistedById(deviceId);
1701
- if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
1702
- const ops = requireDeviceOps(deviceId);
1703
- const sources = await ops.getStreamSources({ deviceId });
1704
- return sources.map((s) => ({ ...s }));
1705
- },
1706
- getConfigSchema: async (input) => {
1707
- const { deviceId } = input;
1708
- if (registry) {
1709
- const found = resolveDeviceById(registry, deviceId);
1710
- if (found) {
1711
- return found.device.config.entries().map((entry) => ({
1712
- key: entry.key,
1713
- value: entry.value,
1714
- ...entry.description !== void 0 ? { description: entry.description } : {}
1715
- }));
1716
- }
1717
- }
1718
- const persisted = await resolvePersistedById(deviceId);
1719
- if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
1720
- const ops = requireDeviceOps(deviceId);
1721
- const entries = await ops.getConfigEntries({ deviceId });
1722
- return entries.map((e) => ({ ...e }));
1723
- },
1724
- getSettingsSchema: async (input) => {
1725
- const { deviceId } = input;
1726
- if (registry) {
1727
- const found = resolveDeviceById(registry, deviceId);
1728
- if (found) {
1729
- return found.device.getSettingsUISchema();
1730
- }
1731
- }
1732
- const persisted = await resolvePersistedById(deviceId);
1733
- if (!persisted) return null;
1734
- const ops = requireDeviceOps(deviceId);
1735
- const schema = await ops.getSettingsSchema({ deviceId });
1736
- return schema ?? null;
1737
- },
1738
- updateConfig: async (input) => {
1739
- const { deviceId } = input;
1740
- if (registry) {
1741
- const found = resolveDeviceById(registry, deviceId);
1742
- if (found) {
1743
- await found.device.config.setAll(input.values);
1744
- return { success: true };
1745
- }
1746
- }
1747
- const persisted = await resolvePersistedById(deviceId);
1748
- if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
1749
- const ops = requireDeviceOps(deviceId);
1750
- await ops.setConfig({ deviceId, values: input.values });
1751
- return { success: true };
1752
- },
1753
- // `enable` / `disable` write to deviceMeta.disabled (the canonical
1754
- // soft-disable flag that drivers consult via `BaseDevice.disabled`
1755
- // at lifecycle entrypoints, and that `toDeviceInfo` projects onto
1756
- // the wire by reading the LATEST persisted meta row — see the
1757
- // `metaRow` argument plumbed through `listAll` / `getDevice` /
1758
- // `getChildren`).
1759
- //
1760
- // Earlier these wrappers wrote `enabled: true/false` into the
1761
- // device CONFIG blob — wrong store entirely. The config write
1762
- // succeeded but the flag the rest of the system reads
1763
- // (deviceMeta) stayed unchanged, so the UI's enable/disable
1764
- // toggle appeared to do nothing. Delegating to `setDisabled`
1765
- // routes through the correct withMetaWriteLock path and emits
1766
- // the `DeviceMetaChanged` event for live invalidation.
1767
- //
1768
- // NB: `BaseDevice.disabled` is `readonly` and bound at
1769
- // construction (base-device.ts:142). Drivers that gate behaviour
1770
- // off `this.disabled` only see the value the device was
1771
- // instantiated with — flipping disabled at runtime updates the
1772
- // wire response immediately, but lifecycle gating inside the
1773
- // driver only takes effect on the next instantiation. That's
1774
- // acceptable today: the operator-facing semantic is "hide /
1775
- // mark inactive in the UI"; the heavyweight teardown semantic
1776
- // is `remove`.
1777
- enable: async (input) => {
1778
- await provider.setDisabled({ deviceId: input.deviceId, disabled: false });
1779
- return { success: true };
1780
- },
1781
- disable: async (input) => {
1782
- await provider.setDisabled({ deviceId: input.deviceId, disabled: true });
1783
- return { success: true };
1784
- },
1785
- remove: async (input) => {
1786
- const { deviceId } = input;
1787
- if (registry) {
1788
- const live = resolveDeviceById(registry, deviceId);
1789
- if (live) {
1790
- const deviceName = live.device.name;
1791
- await live.device.removeDevice();
1792
- registry.remove(deviceId);
1793
- await provider.removeDevice({ deviceId });
1794
- this.ctx.logger.info("removed hub-local device", { tags: { deviceId, deviceName } });
1795
- return { success: true };
1796
- }
1797
- }
1798
- const persisted = await resolvePersistedById(deviceId);
1799
- if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
1800
- const { meta: persistedMeta } = persisted;
1801
- try {
1802
- const ops = requireDeviceOps(deviceId);
1803
- await ops.removeDevice({ deviceId });
1804
- } catch (err) {
1805
- this.ctx.logger.warn("remove via device-ops failed \u2014 clearing persistence anyway", { tags: { deviceId, deviceName: persistedMeta.name }, meta: { error: (0, import_types.errMsg)(err) } });
1806
- }
1807
- await provider.removeDevice({ deviceId });
1808
- return { success: true };
1809
- },
1810
- getStreamProfileMap: async (input) => {
1811
- if (!registry) return {};
1812
- const found = resolveDeviceById(registry, input.deviceId);
1813
- if (!found) return {};
1814
- const storedMap = found.device.config.entries().find((e) => e.key === "_profileMap")?.value;
1815
- if (storedMap !== void 0 && typeof storedMap === "object" && storedMap !== null) {
1816
- return storedMap;
1817
- }
1818
- if (!isCameraDevice(found.device)) return {};
1819
- const sources = await found.device.getStreamSources();
1820
- const profileMap = {};
1821
- for (const s of sources) {
1822
- if (s.profileHint && s.id) {
1823
- profileMap[s.profileHint] = s.id;
1824
- }
1825
- }
1826
- return profileMap;
1827
- },
1828
- setStreamProfileMap: async (input) => {
1829
- const { deviceId } = input;
1830
- if (registry) {
1831
- const found = resolveDeviceById(registry, deviceId);
1832
- if (found) {
1833
- await found.device.config.setAll({ _profileMap: input.profileMap });
1834
- return { success: true };
1835
- }
1836
- }
1837
- const persisted = await resolvePersistedById(deviceId);
1838
- if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
1839
- const ops = requireDeviceOps(deviceId);
1840
- await ops.setConfig({ deviceId, values: { _profileMap: input.profileMap } });
1841
- return { success: true };
1842
- },
1843
- probeStreams: async (input) => {
1844
- const streamProbe = this.ctx.kernel.streamProbe;
1845
- if (!streamProbe) return [];
1846
- const sources = await provider.getStreamSources({ deviceId: input.deviceId });
1847
- const results = [];
1848
- for (const s of sources) {
1849
- if (!s.url) continue;
1850
- try {
1851
- const metadata = await streamProbe.probe(s.url, { force: true });
1852
- results.push({
1853
- streamId: s.id,
1854
- width: metadata.width,
1855
- height: metadata.height,
1856
- codec: metadata.codec,
1857
- fps: metadata.fps,
1858
- bitrateKbps: metadata.bitrateKbps
1859
- });
1860
- } catch (err) {
1861
- this.ctx.logger.debug("streamProbe.probe failed \u2014 returning placeholder", {
1862
- meta: {
1863
- deviceId: input.deviceId,
1864
- streamId: s.id,
1865
- error: err instanceof Error ? err.message : String(err)
1866
- }
1867
- });
1868
- results.push({ streamId: s.id });
1869
- }
1870
- }
1871
- return results;
1872
- },
1873
- // ── Device-provider operations (routed via CapabilityRegistry) ───────
1874
- discoverDevices: async (input) => {
1875
- const dp = await this.requireDeviceProvider(input.addonId);
1876
- const supported = await dp.supportsDiscovery({});
1877
- if (!supported) {
1878
- throw new Error(`Addon "${input.addonId}" does not support device discovery`);
1879
- }
1880
- const discovered = await dp.discoverDevices({});
1881
- return discovered.map((d) => ({
1882
- stableId: d.stableId,
1883
- type: d.type,
1884
- suggestedName: d.suggestedName,
1885
- prefilledConfig: d.prefilledConfig
1886
- }));
1887
- },
1888
- adoptDevice: async (input) => {
1889
- const dp = await this.requireDeviceProvider(input.addonId);
1890
- const supported = await dp.supportsDiscovery({});
1891
- if (!supported) {
1892
- throw new Error(`Addon "${input.addonId}" does not support device adoption`);
1893
- }
1894
- return dp.adoptDiscoveredDevice({
1895
- candidate: input.candidate
1896
- });
1897
- },
1898
- getCreationSchema: async (input) => {
1899
- const dp = await this.requireDeviceProvider(input.addonId);
1900
- const supported = await dp.supportsManualCreation({});
1901
- if (!supported) return null;
1902
- const schema = await dp.getChildCreationSchema({ type: input.type });
1903
- return schema ?? null;
1904
- },
1905
- createDevice: async (input) => {
1906
- const dp = await this.requireDeviceProvider(input.addonId);
1907
- const supported = await dp.supportsManualCreation({});
1908
- if (!supported) {
1909
- throw new Error(`Addon "${input.addonId}" does not support manual device creation`);
1910
- }
1911
- return dp.createDevice({ type: input.type, config: input.config });
1912
- },
1913
- testCreationField: async (input) => {
1914
- const dp = await this.requireDeviceProvider(input.addonId);
1915
- return dp.testCreationField({
1916
- type: input.type,
1917
- key: input.key,
1918
- value: input.value,
1919
- ...input.formValues !== void 0 ? { formValues: input.formValues } : {}
1920
- });
1921
- },
1922
- testField: async (input) => {
1923
- const { deviceId } = input;
1924
- let owningAddonId = null;
1925
- if (registry) {
1926
- owningAddonId = registry.getAddonId(deviceId);
1927
- }
1928
- if (!owningAddonId) {
1929
- const persisted = await resolvePersistedById(deviceId);
1930
- owningAddonId = persisted?.addonId ?? null;
1931
- }
1932
- if (!owningAddonId) {
1933
- throw new Error(`Device with id ${deviceId} not found`);
1934
- }
1935
- const dp = await this.waitDeviceProvider(owningAddonId);
1936
- if (!dp) {
1937
- return { status: "ok", labels: [], error: void 0 };
1938
- }
1939
- if (typeof dp.testCreationField !== "function") {
1940
- return { status: "ok", labels: [], error: void 0 };
1941
- }
1942
- return dp.testCreationField({ type: import_types.DeviceType.Camera, key: input.key, value: input.value });
1943
- },
1944
- // ── Bindings — per-device capability provider map ────────────────────
1945
- getBindings: async (input) => {
1946
- const result = await this.getBindings({ deviceId: input.deviceId });
1947
- return { deviceId: input.deviceId, entries: result.entries };
1948
- },
1949
- getAllBindings: async () => {
1950
- return this.getAllBindings();
1951
- },
1952
- setWrapperActive: async (input) => {
1953
- return this.setWrapperActive({
1954
- deviceId: input.deviceId,
1955
- capName: input.capName,
1956
- wrapperAddonId: input.wrapperAddonId,
1957
- active: input.active
1958
- });
1959
- },
1960
- listWrappersForCap: async (input) => this.listWrappersForCap(input),
1961
- listBindableCapsForDeviceType: async (input) => this.listBindableCapsForDeviceType(input),
1962
- // ── Device-details aggregators ──────────────────────────────────────
1963
- getDeviceSettingsAggregate: async (input) => {
1964
- return this.getDeviceAggregate(input.deviceId, "settings");
1965
- },
1966
- getDeviceLiveInfoAggregate: async (input) => {
1967
- return this.getDeviceAggregate(input.deviceId, "live");
1968
- },
1969
- getDeviceAggregate: async (input) => {
1970
- const [settings2, live] = await Promise.all([
1971
- this.getDeviceAggregate(input.deviceId, "settings"),
1972
- this.getDeviceAggregate(input.deviceId, "live")
1973
- ]);
1974
- return { settings: settings2, live };
1975
- },
1976
- updateDeviceField: async (input) => {
1977
- return this.updateDeviceField({
1978
- deviceId: input.deviceId,
1979
- writerCapName: input.writerCapName,
1980
- writerAddonId: input.writerAddonId,
1981
- key: input.key,
1982
- value: input.value
1983
- });
1984
- },
1985
- updateDeviceFieldsBatch: async (input) => {
1986
- return this.updateDeviceFieldsBatch({ deviceId: input.deviceId, changes: input.changes });
1987
- },
1988
- getDeviceStatusAggregate: async (input) => this.getDeviceStatusAggregate(input)
1989
- };
1990
- this.ctx.logger.info("registered device-manager capability", { meta: { liveRegistry: registry !== null } });
1991
- if (registry) {
1992
- this.propagator = new DeviceEventPropagator({
1993
- eventBus: this.ctx.eventBus,
1994
- getParentOf: (id) => registry.getById(id)?.parentDeviceId ?? null,
1995
- logger: {
1996
- warn: (msg, meta) => this.ctx.logger.warn(msg, meta ?? {}),
1997
- debug: (msg, meta) => this.ctx.logger.debug(msg, meta ?? {})
1998
- }
1999
- });
2000
- this.propagator.start();
2001
- this.ctx.logger.info("device-event-propagator started");
2002
- }
2003
- const deviceStateProvider = {
2004
- getSnapshot: async (input) => {
2005
- return this.snapshotForDevice(input.deviceId);
2006
- },
2007
- getCapSlice: async (input) => {
2008
- const perCap = this.stateMirror.get(input.deviceId);
2009
- const slice = perCap?.get(input.capName);
2010
- return slice ? { ...slice } : null;
2011
- },
2012
- // Whole-system warm-boot dump. Iterates the mirror once and
2013
- // returns a deeply-cloned `{[deviceId]: {[capName]: slice}}`
2014
- // payload so callers (SystemManager, dashboards) seed their
2015
- // local mirror with one round-trip instead of N per-device
2016
- // calls. Empty inner record for devices with no slices yet.
2017
- getAllSnapshots: async () => {
2018
- const out = {};
2019
- for (const [deviceId, perCap] of this.stateMirror) {
2020
- const dev = {};
2021
- for (const [capName, slice] of perCap) dev[capName] = { ...slice };
2022
- out[String(deviceId)] = dev;
2023
- }
2024
- return out;
2025
- },
2026
- // Canonical cross-layer write — the single entrypoint every
2027
- // caller funnels through. In-process providers reach it via
2028
- // `BaseDevice.runtimeState.setCapState` (which delegates here);
2029
- // system-scope addons (e.g. pipeline runner writing the motion
2030
- // slice on phase transitions) call this cap method directly
2031
- // through `ctx.api.deviceState.setCapSlice.mutate(...)`.
2032
- setCapSlice: async (input) => {
2033
- const { deviceId, capName, slice } = input;
2034
- const persisted = await resolvePersistedById(deviceId);
2035
- if (!persisted) throw new Error(`[device-manager] setCapSlice: unknown device id=${deviceId}`);
2036
- this.applySingleCapUpdate(deviceId, capName, slice);
2037
- this.scheduleRuntimeStateDiskWrite(deviceId, settings);
2038
- }
2039
- };
2040
- return [
2041
- { capability: import_types4.deviceManagerCapability, provider },
2042
- { capability: import_types4.deviceStateCapability, provider: deviceStateProvider }
2043
- ];
2044
- }
2045
- /**
2046
- * Single-cap mirror update — diff against the current mirror,
2047
- * persist the new slice in-memory, emit `DeviceStateChanged` for
2048
- * this cap. No-op on identical writes (both same shape and same
2049
- * values). Called by `setCapSlice` provider.
2050
- */
2051
- applySingleCapUpdate(deviceId, capName, slice) {
2052
- let perCap = this.stateMirror.get(deviceId);
2053
- if (!perCap) {
2054
- perCap = /* @__PURE__ */ new Map();
2055
- this.stateMirror.set(deviceId, perCap);
2056
- }
2057
- const prior = perCap.get(capName);
2058
- if (prior && shallowEqual(prior, slice)) return;
2059
- perCap.set(capName, { ...slice });
2060
- this.emitStateChanged(deviceId, capName, slice);
2061
- }
2062
- /**
2063
- * Debounced disk writer. Coalesces frequent writes (motion phase
2064
- * transitions, battery pushes) into one `writeDeviceRuntimeState`
2065
- * per `RUNTIME_STATE_DEBOUNCE_MS` window. Reads the per-device
2066
- * blob from the live mirror at flush time so the disk picture is
2067
- * always the latest state — no risk of writing a stale snapshot.
2068
- */
2069
- scheduleRuntimeStateDiskWrite(deviceId, settings) {
2070
- let slot = this.runtimeStateDebounce.get(deviceId);
2071
- if (!slot) {
2072
- slot = { timer: null, inFlight: null };
2073
- this.runtimeStateDebounce.set(deviceId, slot);
2074
- }
2075
- if (slot.timer) return;
2076
- slot.timer = setTimeout(() => {
2077
- slot.timer = null;
2078
- const blob = this.snapshotForDevice(deviceId);
2079
- const write = (async () => {
2080
- try {
2081
- await settings.writeDeviceRuntimeState(deviceId, blob);
2082
- } catch (err) {
2083
- this.ctx.logger.warn("writeDeviceRuntimeState failed", {
2084
- tags: { deviceId },
2085
- meta: { error: err instanceof Error ? err.message : String(err) }
2086
- });
2087
- } finally {
2088
- slot.inFlight = null;
2089
- }
2090
- })();
2091
- slot.inFlight = write;
2092
- }, _DeviceManagerAddon.RUNTIME_STATE_DEBOUNCE_MS);
2093
- }
2094
- /**
2095
- * One-shot mirror seed used by `loadRuntimeState` at boot so the
2096
- * hub knows about every persisted slice without waiting for the
2097
- * first `setCapSlice` call. No events emitted — this is
2098
- * initial-state population, not a transition.
2099
- */
2100
- seedMirror(deviceId, blob) {
2101
- let perCap = this.stateMirror.get(deviceId);
2102
- if (!perCap) {
2103
- perCap = /* @__PURE__ */ new Map();
2104
- this.stateMirror.set(deviceId, perCap);
2105
- }
2106
- for (const [capName, raw] of Object.entries(blob)) {
2107
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
2108
- perCap.set(capName, { ...raw });
2109
- }
2110
- }
2111
- snapshotForDevice(deviceId) {
2112
- const perCap = this.stateMirror.get(deviceId);
2113
- if (!perCap) return {};
2114
- const out = {};
2115
- for (const [k, v] of perCap) out[k] = { ...v };
2116
- return out;
2117
- }
2118
- emitStateChanged(deviceId, capName, slice) {
2119
- this.ctx.eventBus.emit({
2120
- id: (0, import_node_crypto.randomUUID)(),
2121
- timestamp: /* @__PURE__ */ new Date(),
2122
- source: { type: "device", id: deviceId },
2123
- category: import_types.EventCategory.DeviceStateChanged,
2124
- data: { deviceId, capName, slice }
2125
- });
2126
- }
2127
- async onShutdown() {
2128
- this.propagator?.stop();
2129
- this.propagator = null;
2130
- const settings = this.ctx.settings;
2131
- const pending = [];
2132
- for (const [deviceId, slot] of this.runtimeStateDebounce) {
2133
- if (slot.timer) {
2134
- clearTimeout(slot.timer);
2135
- slot.timer = null;
2136
- if (settings) {
2137
- const blob = this.snapshotForDevice(deviceId);
2138
- pending.push(settings.writeDeviceRuntimeState(deviceId, blob).catch((err) => {
2139
- this.ctx.logger.warn("shutdown writeDeviceRuntimeState failed", {
2140
- tags: { deviceId },
2141
- meta: { error: err instanceof Error ? err.message : String(err) }
2142
- });
2143
- }));
2144
- }
2145
- }
2146
- if (slot.inFlight) pending.push(slot.inFlight);
2147
- }
2148
- await Promise.all(pending);
2149
- this.runtimeStateDebounce.clear();
2150
- }
2151
- };
2152
- var device_manager_addon_default = DeviceManagerAddon;
2153
- // Annotate the CommonJS export names for ESM import in node:
2154
- 0 && (module.exports = {
2155
- DeviceManagerAddon
2156
- });
2157
- //# sourceMappingURL=index.js.map
5
+ const require_builtins_device_manager_device_manager_addon = require("./device-manager.addon.js");
6
+ exports.DeviceManagerAddon = require_builtins_device_manager_device_manager_addon.DeviceManagerAddon;
7
+ exports.default = require_builtins_device_manager_device_manager_addon.DeviceManagerAddon;