@camstack/server 1.2.918 → 1.2.920

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 (96) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/package.json +7 -9
  3. package/system/dist/addon-utils.mjs +1 -1
  4. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +1 -1
  5. package/system/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +4 -4
  6. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +1 -1
  7. package/system/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +5 -5
  8. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  9. package/system/dist/builtins/alerts/alerts.addon.mjs +3 -3
  10. package/system/dist/builtins/autotrack/index.js +1 -1
  11. package/system/dist/builtins/autotrack/index.mjs +1 -1
  12. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.js +2 -2
  13. package/system/dist/builtins/backup-orchestrator/backup-orchestrator.addon.mjs +5 -5
  14. package/system/dist/builtins/calendars/calendars.addon.js +1 -1
  15. package/system/dist/builtins/calendars/calendars.addon.mjs +1 -1
  16. package/system/dist/builtins/camera-grid/index.js +1 -1
  17. package/system/dist/builtins/camera-grid/index.mjs +1 -1
  18. package/system/dist/builtins/composer/composer.addon.js +4 -4
  19. package/system/dist/builtins/composer/composer.addon.mjs +4 -4
  20. package/system/dist/builtins/console-logging/index.js +1 -1
  21. package/system/dist/builtins/console-logging/index.mjs +1 -1
  22. package/system/dist/builtins/core-blocks/core-blocks.addon.js +4 -4
  23. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +4 -4
  24. package/system/dist/builtins/device-history/device-history.addon.js +2 -2
  25. package/system/dist/builtins/device-history/device-history.addon.mjs +2 -2
  26. package/system/dist/builtins/device-manager/device-manager.addon.js +19 -1132
  27. package/system/dist/builtins/device-manager/device-manager.addon.mjs +11 -1123
  28. package/system/dist/builtins/hub-forwarder/index.js +1 -1
  29. package/system/dist/builtins/hub-forwarder/index.mjs +1 -1
  30. package/system/dist/builtins/keychain/index.js +4 -4
  31. package/system/dist/builtins/keychain/index.mjs +4 -4
  32. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.js +1 -1
  33. package/system/dist/builtins/liveness-monitor/liveness-monitor.addon.mjs +1 -1
  34. package/system/dist/builtins/local-auth/local-auth.addon.js +2 -2
  35. package/system/dist/builtins/local-auth/local-auth.addon.mjs +5 -5
  36. package/system/dist/builtins/local-network/local-network.addon.js +3 -3
  37. package/system/dist/builtins/local-network/local-network.addon.mjs +3 -3
  38. package/system/dist/builtins/loki-logging/index.js +1 -1
  39. package/system/dist/builtins/loki-logging/index.mjs +1 -1
  40. package/system/dist/builtins/native-metrics/native-metrics.addon.js +1 -1
  41. package/system/dist/builtins/native-metrics/native-metrics.addon.mjs +10 -10
  42. package/system/dist/builtins/platform-probe/index.js +1 -1
  43. package/system/dist/builtins/platform-probe/index.mjs +10 -10
  44. package/system/dist/builtins/record-entries/index.js +1 -1
  45. package/system/dist/builtins/record-entries/index.mjs +1 -1
  46. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.js +1 -1
  47. package/system/dist/builtins/remote-access-orchestrator/remote-access-orchestrator.addon.mjs +1 -1
  48. package/system/dist/builtins/snapshot/index.js +1 -1
  49. package/system/dist/builtins/snapshot/index.mjs +1 -1
  50. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.js +1 -1
  51. package/system/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +20 -20
  52. package/system/dist/builtins/sqlite-storage/index.js +1 -1
  53. package/system/dist/builtins/sqlite-storage/index.mjs +1 -1
  54. package/system/dist/builtins/sqlite-storage/migrations/migration-edits.d.ts +31 -5
  55. package/system/dist/builtins/sqlite-storage/migrations/migration-pass.d.ts +5 -5
  56. package/system/dist/builtins/sqlite-storage/migrations/migration-types.d.ts +15 -1
  57. package/system/dist/builtins/sqlite-storage/records/records-engine.d.ts +7 -0
  58. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.js +4 -4
  59. package/system/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +4 -4
  60. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.js +1 -1
  61. package/system/dist/builtins/storage-orchestrator/storage-orchestrator.addon.mjs +1 -1
  62. package/system/dist/builtins/system-config/system-config.addon.js +3 -3
  63. package/system/dist/builtins/system-config/system-config.addon.mjs +115 -115
  64. package/system/dist/builtins/winston-logging/index.js +1 -1
  65. package/system/dist/builtins/winston-logging/index.mjs +1 -1
  66. package/system/dist/{capture-engine-CMZtj4AD.js → capture-engine-Bb6tKNBs.js} +1 -1
  67. package/system/dist/{capture-engine-CoefzcsI.mjs → capture-engine-CjHR3sw5.mjs} +1 -1
  68. package/system/dist/{composition-sources-Bq4EFdKT.js → composition-sources-ButoG4Fn.js} +1 -1
  69. package/system/dist/{composition-sources-BVndKBya.mjs → composition-sources-ChuEYTTM.mjs} +1 -1
  70. package/system/dist/{constants-VKa3Y_M7.mjs → constants-CTgI2UJT.mjs} +1 -1
  71. package/system/dist/{constants-DOBw7N2s.js → constants-DCLxwooy.js} +1 -1
  72. package/system/dist/{coral-accelerators-DBlgWB8k.mjs → coral-accelerators-BW3OcrLD.mjs} +6 -6
  73. package/system/dist/{custom-action-registry-B9zFBNVa.mjs → custom-action-registry-N7flBDwT.mjs} +37 -37
  74. package/system/dist/{device-ca-BYXNhG52.js → device-ca-CAEJ3dvi.js} +1 -1
  75. package/system/dist/{device-ca-C9a-1Q9D.mjs → device-ca-CAnFM1ic.mjs} +1 -1
  76. package/system/dist/device-row-store-DE8I2-Zv.mjs +1113 -0
  77. package/system/dist/device-row-store-DMKWs6YZ.js +1143 -0
  78. package/system/dist/{dist-DQGk7XcX.mjs → dist-Ce7JDvHm.mjs} +775 -4
  79. package/system/dist/{dist-BvoilCmO.js → dist-CxIM-RDP.js} +786 -3
  80. package/system/dist/file-host-worker.js +2 -2
  81. package/system/dist/file-host-worker.mjs +2 -2
  82. package/system/dist/{hub-identity-CN6z_g2b.mjs → hub-identity-B7qOTvnj.mjs} +10 -10
  83. package/system/dist/{hub-identity-B_r524vf.js → hub-identity-BFhHu01s.js} +1 -1
  84. package/system/dist/{hub-mdns-ciao-5HHfcwfK.js → hub-mdns-ciao-BCC9aBJ9.js} +2 -2
  85. package/system/dist/{hub-mdns-ciao-Dmaledqs.mjs → hub-mdns-ciao-CmLHZFrF.mjs} +2 -2
  86. package/system/dist/index.js +8 -8
  87. package/system/dist/index.mjs +217 -217
  88. package/system/dist/{legacy-integration-rows-door-BgMMdawG.mjs → legacy-integration-rows-door-AwqTvP7Q.mjs} +1 -1
  89. package/system/dist/{legacy-integration-rows-door-tRQ5ufny.js → legacy-integration-rows-door-DRXlHLld.js} +1 -1
  90. package/system/dist/{rename-composition-block-CMP2cY6o.js → rename-composition-block-Cr_M-06e.js} +1 -1
  91. package/system/dist/{rename-composition-block-D7WfspkB.mjs → rename-composition-block-dOnhNmEv.mjs} +1 -1
  92. package/system/dist/{restore-archive-BDj4MPWq.mjs → restore-archive-BDdB1JLF.mjs} +94 -94
  93. package/system/dist/{restore-archive-DLJV-MXM.js → restore-archive-Bw3R2AlD.js} +1 -1
  94. package/system/dist/{wal-maintenance-CIEBmJaJ.js → wal-maintenance-CjIr-KYB.js} +0 -0
  95. package/system/dist/{wal-maintenance-CvVAKiFr.mjs → wal-maintenance-r-TlhM3d.mjs} +0 -0
  96. package/system/package.json +1 -1
@@ -0,0 +1,1143 @@
1
+ const require_dist = require("./dist-CxIM-RDP.js");
2
+ //#region src/builtins/device-manager/migration-refused.ts
3
+ /**
4
+ * A migration step that REFUSED with nothing moved.
5
+ *
6
+ * `migrateDevice` distinguishes two kinds of failure after the disable phase,
7
+ * and they must never be confused (D663 task 5b ruling I-1):
8
+ *
9
+ * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
10
+ * temp id taken), the mirror drain that runs before the rows move, or a
11
+ * claim found in the mirror after that drain (it landed while the migration
12
+ * was starting). Both cameras are switched back to exactly what they were,
13
+ * because nothing about either device changed.
14
+ * - **failed while moving** — any other throw from `swapIds` (rows partially
15
+ * moved), or from `swapHardwareState` (rows swapped, state not). The two
16
+ * devices may wear each other's identity; switching them back on would run
17
+ * pipelines against crossed identities, so they stay off and the operator is
18
+ * told to intervene.
19
+ *
20
+ * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
21
+ * read as "may have moved" — the safe reading.
22
+ */
23
+ var MigrationRefusedError = class extends Error {
24
+ constructor(message, options) {
25
+ super(message, options);
26
+ this.name = "MigrationRefusedError";
27
+ }
28
+ };
29
+ var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
30
+ var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
31
+ tombstones: {
32
+ schema: DeviceTombstoneBodySchema,
33
+ class: "ledger",
34
+ writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
35
+ device: "none",
36
+ at: "required",
37
+ indexes: [{
38
+ name: "deleted_at",
39
+ fields: ["deletedAt"]
40
+ }],
41
+ retention: {
42
+ owner: "device-manager",
43
+ reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
44
+ }
45
+ },
46
+ "discovery-proposals": {
47
+ schema: require_dist.DiscoveryProposalBodySchema,
48
+ class: "config",
49
+ writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
50
+ device: "none",
51
+ at: "required",
52
+ indexes: [{
53
+ name: "last_seen_at",
54
+ fields: ["lastSeenAt"]
55
+ }],
56
+ retention: {
57
+ ttlMs: 2160 * 60 * 60 * 1e3,
58
+ from: "at"
59
+ }
60
+ },
61
+ "identity-links": {
62
+ schema: require_dist.IdentityLinkBodySchema,
63
+ class: "config",
64
+ writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
65
+ device: "none",
66
+ at: "none",
67
+ indexes: [{
68
+ name: "a_device",
69
+ fields: ["a.deviceId"]
70
+ }, {
71
+ name: "b_device",
72
+ fields: ["b.deviceId"]
73
+ }],
74
+ retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
75
+ }
76
+ });
77
+ var deviceManagerRecordKinds = _deviceManagerRecordKinds;
78
+ _deviceManagerRecordKinds.tombstones;
79
+ //#endregion
80
+ //#region src/builtins/device-manager/fleet-read-census.ts
81
+ /** How many stack frames identify a call site. One frame is a method; three are
82
+ * a cause — `listFleet < listAll < onDeviceRegistered` is the answer, `listAll`
83
+ * alone is not. Same choice, for the same reason, as `read-census.ts`. */
84
+ var CENSUS_STACK_FRAMES = 3;
85
+ function siteFromStack(stack) {
86
+ if (stack === void 0) return "unknown";
87
+ const frames = stack.split("\n").slice(1).map((line) => line.trim().replace(/^at\s+/, "")).filter((line) => line.length > 0).slice(0, CENSUS_STACK_FRAMES).map((line) => {
88
+ const open = line.indexOf(" (");
89
+ return (open > 0 ? line.slice(0, open) : line).replace(/^async\s+/, "");
90
+ });
91
+ return frames.length === 0 ? "unknown" : frames.join(" < ");
92
+ }
93
+ var FleetReadCensus = class FleetReadCensus {
94
+ /**
95
+ * Longest window the census may be armed for.
96
+ *
97
+ * Ten minutes covers a boot several times over and bounds what an operator
98
+ * pays if they set the variable and forget it. A diagnostic that can be left
99
+ * on becomes a tax nobody remembers enabling.
100
+ */
101
+ static MAX_WINDOW_MS = 10 * 6e4;
102
+ windowMs;
103
+ closesAt;
104
+ counts = /* @__PURE__ */ new Map();
105
+ reported = false;
106
+ constructor(rawEnv, nowMs) {
107
+ const parsed = rawEnv === void 0 ? NaN : Number(rawEnv);
108
+ const valid = Number.isFinite(parsed) && parsed > 0;
109
+ this.windowMs = valid ? Math.min(parsed, FleetReadCensus.MAX_WINDOW_MS) : 0;
110
+ this.closesAt = valid ? nowMs + this.windowMs : 0;
111
+ }
112
+ get armed() {
113
+ return this.windowMs > 0;
114
+ }
115
+ /** Test seam: pretend the window closed. Production reads the clock. */
116
+ closeAt(nowMs) {
117
+ if (nowMs >= this.closesAt) this.forceClosed = true;
118
+ }
119
+ forceClosed = false;
120
+ isOpen(nowMs) {
121
+ if (!this.armed || this.forceClosed) return false;
122
+ return nowMs < this.closesAt;
123
+ }
124
+ /**
125
+ * Capture the caller, or `null` when the window is shut.
126
+ *
127
+ * Called at the START of a read. A read that began inside the window belongs
128
+ * to it even if it lands after the close — otherwise the slow reads at the
129
+ * edge would be attributed to nobody, and the slow ones are the interesting
130
+ * ones.
131
+ *
132
+ * `callerAddonId`, when given, is formatted as the site VERBATIM instead of
133
+ * walking the local stack. A call that arrived over the cap channel — a
134
+ * forked addon's `ctx.api.deviceManager.listAll.query()`, routed through
135
+ * `LocalChildRegistry` → `onUnownedCall` → `CapRouteResolver` — carries its
136
+ * origin as DATA (the registered `childId` the parent captured off the UDS
137
+ * connection), and no amount of stack depth would ever recover it: every
138
+ * frame between the socket read and this call is the SAME generic
139
+ * dispatcher code (`onUnownedCall`, `dispatch`, `invoke`) regardless of
140
+ * which addon called — the 2026-08-25 boot census measured this directly,
141
+ * five thousand calls landing on `listAll` with nothing nameable above it.
142
+ *
143
+ * `isOpen` is checked FIRST, before the id is even looked at — a caller
144
+ * threading a (cheap, already-known) `callerAddonId` through on every
145
+ * request, armed or not, must not pay for the template string when
146
+ * disarmed. This is also why formatting lives HERE rather than at the call
147
+ * site: `DeviceRowStore` passes the raw id through unconditionally, and
148
+ * only this method — which already knows whether armed — decides whether
149
+ * to spend anything on it.
150
+ */
151
+ siteOf(callerAddonId, nowMs = Date.now()) {
152
+ if (!this.isOpen(nowMs)) return null;
153
+ if (callerAddonId !== void 0) return `addon:${callerAddonId}`;
154
+ const holder = {};
155
+ Error.captureStackTrace(holder, this.siteOf);
156
+ return siteFromStack(holder.stack);
157
+ }
158
+ /** Count one read at an already-captured site. A `null` site is not counted. */
159
+ record(site, rowCount) {
160
+ if (site === null) return;
161
+ const existing = this.counts.get(site);
162
+ if (existing === void 0) {
163
+ this.counts.set(site, {
164
+ site,
165
+ calls: 1,
166
+ rows: rowCount
167
+ });
168
+ return;
169
+ }
170
+ existing.calls += 1;
171
+ existing.rows += rowCount;
172
+ }
173
+ /** Attributed sites, busiest first. */
174
+ rows() {
175
+ return [...this.counts.values()].map((c) => ({
176
+ site: c.site,
177
+ calls: c.calls,
178
+ rows: c.rows
179
+ })).sort((a, b) => b.calls - a.calls);
180
+ }
181
+ /**
182
+ * Emit the report ONCE.
183
+ *
184
+ * `perMin` is included because the raw count is unreadable without the window
185
+ * it was taken over — "4 149" means nothing until you know it was 66 seconds.
186
+ */
187
+ report(logger, elapsedMs) {
188
+ if (this.reported || !this.armed) return;
189
+ this.reported = true;
190
+ const rows = this.rows();
191
+ const totalCalls = rows.reduce((acc, r) => acc + r.calls, 0);
192
+ logger.info("fleet read census", { meta: {
193
+ elapsedMs,
194
+ sites: rows.length,
195
+ totalCalls,
196
+ rows: rows.map((r) => ({
197
+ site: r.site,
198
+ calls: r.calls,
199
+ rows: r.rows,
200
+ perMin: elapsedMs === 0 ? 0 : Math.round(r.calls * 6e4 / elapsedMs)
201
+ }))
202
+ } });
203
+ }
204
+ };
205
+ //#endregion
206
+ //#region src/builtins/device-manager/device-row-store.ts
207
+ /**
208
+ * `device-manager:devices` — ONE ROW PER DEVICE.
209
+ *
210
+ * ## What this replaces
211
+ *
212
+ * The device-manager used to keep its whole fleet in three JSON blobs on the
213
+ * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
214
+ * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
215
+ * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
216
+ * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
217
+ * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
218
+ * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
219
+ * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
220
+ * through the meta store, and every runner's first store read queued behind it.
221
+ *
222
+ * Writing was worse than reading. `ConfigManager.createSettingsView`'s
223
+ * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
224
+ * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
225
+ * camera rewrote 625 KB.
226
+ *
227
+ * A row per device makes the per-device question a primary-key lookup and the
228
+ * per-device write a single-row upsert touching only the columns named.
229
+ *
230
+ * ## Why `deviceIndex` has no column and no collection
231
+ *
232
+ * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
233
+ * and `stableId` are fields of every row, so "this addon's devices" is
234
+ * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
235
+ * membership meant "`registerDevice` has run at least once", which is how
236
+ * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
237
+ * meta refresh. `allocateDeviceId` writes a row without registering, so row
238
+ * existence alone cannot answer it. That bit is the {@link registered} column,
239
+ * and nothing else of `deviceIndex` survives.
240
+ *
241
+ * ## Why metadata is a column and not a second collection
242
+ *
243
+ * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
244
+ * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
245
+ * had to preserve a `metadata` field would eventually clobber a concurrent
246
+ * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
247
+ * problem — `set` names its columns and leaves the rest of the row untouched —
248
+ * so the split has no reason to exist and metadata rides on the device's own
249
+ * row.
250
+ *
251
+ * ## Adding a column later
252
+ *
253
+ * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
254
+ * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
255
+ * to a populated table, so the backend counts it as non-additive and REBUILDS
256
+ * the collection — dropping every row. Any column added here after ship must
257
+ * either be nullable or carry a `defaultValue`.
258
+ */
259
+ /**
260
+ * @durable class=ledger owner=device-manager
261
+ * write="one row per device, written by `allocateDeviceId` (identity placeholder),
262
+ * `registerDevice` (full reconcile) and every meta setter (single-column patch);
263
+ * `setMetadata` patches the `metadata` column of the same row"
264
+ * retention="none — a row goes only when the operator removes the device
265
+ * (`removeDevice`), or when an integration is deleted and cascades. Bounded by the
266
+ * fleet an operator configures (974 rows on the reference hub)."
267
+ *
268
+ * ### Why `ledger` and not `config`
269
+ *
270
+ * This shipped as `class=registry`, a sixth class that does not exist —
271
+ * `DURABLE_CLASSES` is `ledger | mirror | ephemeral | config | audit`, so
272
+ * `check-durable-state-declared.ts` has failed since. `config` is the tempting
273
+ * answer, because a device's `name` and `location` ARE operator intent. It is
274
+ * the wrong one, and wrong in the dangerous direction: `config`'s rule is
275
+ * *"already durable everywhere"*, and that is exactly the premise that made the
276
+ * dead `devices` table look harmless right up to D183.
277
+ *
278
+ * Nothing else holds a device's NUMERIC id. `allocateDeviceId` mints it here
279
+ * and every other store in the system keys on it — `addon-device-settings`,
280
+ * `device-runtime-state`, every `pipeline-analytics:*` row, every recorder path.
281
+ * That is `ledger`'s definition verbatim ("a fact only this component ever
282
+ * held"), and `ledger`'s rule — *must not be pruned against a fallible read* —
283
+ * is precisely the rule this collection needs (D49): a `getBindings` or an
284
+ * integration listing that answers empty because it FAILED must never be
285
+ * allowed to retire a device row.
286
+ */
287
+ var DEVICE_ROWS_COLLECTION = "device-manager:devices";
288
+ /**
289
+ * Fleet reads pass this explicitly.
290
+ *
291
+ * `settings-store.query` applies a DEFAULT row cap of 2 000 when the caller
292
+ * names no `limit` (`query-bounds.ts`), and truncation there is silent to the
293
+ * caller — it warns in the engine's log and returns a short list that looks
294
+ * complete. The reference hub is already at 974 devices; half the default cap
295
+ * is not a margin worth betting the fleet listing on. 20 000 is the engine's
296
+ * hard ceiling, so this asks for everything the engine will ever serve in one
297
+ * call and any future need to page is a loud failure rather than a quiet one.
298
+ */
299
+ var DEVICE_ROWS_FLEET_LIMIT = 2e4;
300
+ var DEVICE_ROWS_COLUMNS = [
301
+ {
302
+ name: "id",
303
+ type: "TEXT",
304
+ primaryKey: true,
305
+ notNull: true
306
+ },
307
+ {
308
+ name: "deviceId",
309
+ type: "INTEGER",
310
+ notNull: true
311
+ },
312
+ {
313
+ name: "addonId",
314
+ type: "TEXT",
315
+ notNull: true
316
+ },
317
+ {
318
+ name: "stableId",
319
+ type: "TEXT",
320
+ notNull: true
321
+ },
322
+ {
323
+ name: "type",
324
+ type: "TEXT",
325
+ notNull: true
326
+ },
327
+ {
328
+ name: "name",
329
+ type: "TEXT",
330
+ notNull: true
331
+ },
332
+ {
333
+ name: "alias",
334
+ type: "TEXT"
335
+ },
336
+ {
337
+ name: "userNamed",
338
+ type: "BOOLEAN"
339
+ },
340
+ {
341
+ name: "location",
342
+ type: "TEXT"
343
+ },
344
+ {
345
+ name: "tags",
346
+ type: "JSON"
347
+ },
348
+ {
349
+ name: "disabled",
350
+ type: "BOOLEAN",
351
+ notNull: true,
352
+ defaultValue: false
353
+ },
354
+ {
355
+ name: "parentDeviceId",
356
+ type: "INTEGER"
357
+ },
358
+ {
359
+ name: "registered",
360
+ type: "BOOLEAN",
361
+ notNull: true,
362
+ defaultValue: false
363
+ },
364
+ {
365
+ name: "features",
366
+ type: "JSON"
367
+ },
368
+ {
369
+ name: "exportFingerprint",
370
+ type: "TEXT"
371
+ },
372
+ {
373
+ name: "integrationId",
374
+ type: "TEXT"
375
+ },
376
+ {
377
+ name: "linkDeviceId",
378
+ type: "INTEGER"
379
+ },
380
+ {
381
+ name: "primaryChildEntityId",
382
+ type: "TEXT"
383
+ },
384
+ {
385
+ name: "childLayout",
386
+ type: "JSON"
387
+ },
388
+ {
389
+ name: "primaryChildPreference",
390
+ type: "JSON"
391
+ },
392
+ {
393
+ name: "role",
394
+ type: "TEXT"
395
+ },
396
+ {
397
+ name: "display",
398
+ type: "JSON"
399
+ },
400
+ {
401
+ name: "metadata",
402
+ type: "JSON"
403
+ },
404
+ {
405
+ name: "identifiers",
406
+ type: "JSON"
407
+ },
408
+ {
409
+ name: "attachedIdentifiers",
410
+ type: "JSON"
411
+ },
412
+ {
413
+ name: "attachedRetained",
414
+ type: "JSON"
415
+ }
416
+ ];
417
+ /**
418
+ * The columns a SLIM fleet read selects: every declared column except the
419
+ * primary key (always returned) and `metadata`.
420
+ *
421
+ * ## Why this is a DENYLIST and must stay one
422
+ *
423
+ * `decodeDeviceRow` returns `null` when `deviceId`, `addonId`, `stableId`,
424
+ * `type` or `name` is missing, and `list()` then SKIPS the row with a warn. A
425
+ * hand-written allowlist that forgot one of the five would not make the fleet
426
+ * slower — it would make devices vanish from every listing, quietly, and the
427
+ * only trace would be a log line nobody is reading at the time. Deriving the
428
+ * list by subtraction means a column added tomorrow is carried by default and
429
+ * the only way to lose one is to name it here.
430
+ *
431
+ * `metadata` is the one slim provably discards: `device-queries.ts#listAll`
432
+ * sets `metadata: null` on every slim row. It is also the largest JSON column
433
+ * on the row, which is why this is worth doing at all.
434
+ *
435
+ * ## What is NOT here, and will not be
436
+ *
437
+ * There is no `where: { type: 'camera' }` companion to this. `isCameraDevice`
438
+ * is a method-presence check (`getStreamSources`), not the persisted `type`, so
439
+ * a doorbell with a camera answers YES while its row says `doorbell`. Filtering
440
+ * the rows by type would strip exactly those devices of their row — and
441
+ * `toDeviceInfo` reads `name` / `location` / `disabled` from the ROW precisely
442
+ * because the live device's copies are stale by construction. The fleet would
443
+ * keep working and start reporting pre-rename names on doorbells. The
444
+ * `isCamera` filter stays in JS.
445
+ */
446
+ var DEVICE_ROWS_SLIM_COLUMNS = DEVICE_ROWS_COLUMNS.map((c) => c.name).filter((name) => name !== "id" && name !== "metadata");
447
+ var DEVICE_ROWS_INDEXES = [
448
+ {
449
+ name: "idx_dm_devices_addon_stable",
450
+ columns: ["addonId", "stableId"]
451
+ },
452
+ {
453
+ name: "idx_dm_devices_parent",
454
+ columns: ["parentDeviceId"]
455
+ },
456
+ {
457
+ name: "idx_dm_devices_integration",
458
+ columns: ["integrationId"]
459
+ },
460
+ {
461
+ name: "idx_dm_devices_alias",
462
+ columns: ["alias"]
463
+ }
464
+ ];
465
+ /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
466
+ function deviceRowBackendOf(client) {
467
+ return {
468
+ declareCollection: async (input) => {
469
+ await client.declareCollection.mutate(input);
470
+ },
471
+ get: (input) => client.get.query(input),
472
+ set: async (input) => {
473
+ await client.set.mutate(input);
474
+ },
475
+ query: (input) => client.query.query(input),
476
+ updateWhere: (input) => client.updateWhere.mutate(input),
477
+ delete: async (input) => {
478
+ await client.delete.mutate(input);
479
+ },
480
+ count: (input) => client.count.query(input)
481
+ };
482
+ }
483
+ function isPlainObject(value) {
484
+ return value !== null && typeof value === "object" && !Array.isArray(value);
485
+ }
486
+ function readString(value) {
487
+ return typeof value === "string" ? value : void 0;
488
+ }
489
+ function readNumber(value) {
490
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
491
+ }
492
+ function readBoolean(value) {
493
+ if (typeof value === "boolean") return value;
494
+ if (value === 1) return true;
495
+ if (value === 0) return false;
496
+ }
497
+ function readStringArray(value) {
498
+ if (!Array.isArray(value)) return void 0;
499
+ const out = [];
500
+ for (const entry of value) if (typeof entry === "string") out.push(entry);
501
+ return out;
502
+ }
503
+ /**
504
+ * Decode one stored row.
505
+ *
506
+ * Returns `null` for a row missing an identity field the rest of the system
507
+ * treats as an invariant (`deviceId` / `addonId` / `stableId` / `type` /
508
+ * `name`). A row like that cannot be projected into a `DeviceInfo` and taking
509
+ * the whole fleet read down for it would be worse — the caller logs the skip.
510
+ */
511
+ function decodeDeviceRow(data) {
512
+ const deviceId = readNumber(data["deviceId"]);
513
+ const addonId = readString(data["addonId"]);
514
+ const stableId = readString(data["stableId"]);
515
+ const storedType = readString(data["type"]);
516
+ const type = storedType === void 0 ? void 0 : require_dist.canonicalStoredDeviceType(storedType);
517
+ const name = readString(data["name"]);
518
+ if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
519
+ const location = readString(data["location"]);
520
+ const tags = readStringArray(data["tags"]);
521
+ const parentDeviceId = readNumber(data["parentDeviceId"]);
522
+ const userNamed = readBoolean(data["userNamed"]);
523
+ const features = readStringArray(data["features"]);
524
+ const exportFingerprint = readString(data["exportFingerprint"]);
525
+ const integrationId = readString(data["integrationId"]);
526
+ const linkDeviceId = readNumber(data["linkDeviceId"]);
527
+ const primaryChildEntityId = readString(data["primaryChildEntityId"]);
528
+ const role = readString(data["role"]);
529
+ const alias = readString(data["alias"]);
530
+ const rawChildLayout = data["childLayout"];
531
+ const primaryChildPreference = readStringArray(data["primaryChildPreference"]);
532
+ const rawDisplay = data["display"];
533
+ const rawMetadata = data["metadata"];
534
+ const identifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["identifiers"]);
535
+ const attachedIdentifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
536
+ const attachedRetained = require_dist.DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
537
+ return {
538
+ meta: {
539
+ id: deviceId,
540
+ addonId,
541
+ stableId,
542
+ type,
543
+ name,
544
+ location: location ?? null,
545
+ ...tags !== void 0 && tags.length > 0 ? { tags: [...tags] } : {},
546
+ disabled: readBoolean(data["disabled"]) ?? false,
547
+ parentDeviceId: parentDeviceId ?? null,
548
+ ...alias !== void 0 ? { alias } : {},
549
+ ...userNamed !== void 0 ? { userNamed } : {},
550
+ ...features !== void 0 ? { features } : {},
551
+ ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
552
+ ...integrationId !== void 0 ? { integrationId } : {},
553
+ ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
554
+ ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
555
+ ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
556
+ ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
557
+ ...role !== void 0 ? { role } : {},
558
+ ...isPlainObject(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
559
+ ...identifiers.success ? { identifiers: identifiers.data } : {},
560
+ ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
561
+ ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
562
+ },
563
+ metadata: isPlainObject(rawMetadata) ? rawMetadata : null,
564
+ registered: readBoolean(data["registered"]) ?? false
565
+ };
566
+ }
567
+ /**
568
+ * `ChildLayout` is a JSON column: what comes back is whatever was written.
569
+ * The projection hands it to the UI untouched, so the only thing worth
570
+ * checking is that it is still the array shape the writer put in.
571
+ */
572
+ function isChildLayout(value) {
573
+ return Array.isArray(value);
574
+ }
575
+ /**
576
+ * `DeviceDisplayOverride` is likewise stored verbatim in a JSON column. It is
577
+ * an all-optional record, so any object round-trips; the write path
578
+ * (`normalizeDisplayOverride`) is what gives it shape.
579
+ */
580
+ function toDisplayOverride(value) {
581
+ return value;
582
+ }
583
+ /** Full-row value for an upsert: identity + every field of the meta record. */
584
+ function encodeDeviceRow(meta, extra = {}) {
585
+ const row = {
586
+ id: String(meta.id),
587
+ deviceId: meta.id,
588
+ addonId: meta.addonId,
589
+ stableId: meta.stableId,
590
+ type: meta.type,
591
+ name: meta.name,
592
+ alias: meta.alias ?? null,
593
+ userNamed: meta.userNamed ?? null,
594
+ location: meta.location,
595
+ tags: meta.tags === void 0 || meta.tags.length === 0 ? null : [...meta.tags],
596
+ disabled: meta.disabled,
597
+ parentDeviceId: meta.parentDeviceId,
598
+ registered: extra.registered ?? false,
599
+ features: meta.features === void 0 ? null : [...meta.features],
600
+ exportFingerprint: meta.exportFingerprint ?? null,
601
+ integrationId: meta.integrationId ?? null,
602
+ linkDeviceId: meta.linkDeviceId ?? null,
603
+ primaryChildEntityId: meta.primaryChildEntityId ?? null,
604
+ childLayout: meta.childLayout ?? null,
605
+ primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
606
+ role: meta.role ?? null,
607
+ display: meta.display ?? null,
608
+ identifiers: meta.identifiers ?? null,
609
+ attachedIdentifiers: meta.attachedIdentifiers ?? null,
610
+ attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
611
+ };
612
+ if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
613
+ return row;
614
+ }
615
+ /** Column map for a partial write — only the keys the caller actually named. */
616
+ function encodeDeviceRowPatch(patch) {
617
+ const row = {};
618
+ for (const [key, value] of Object.entries(patch)) {
619
+ if (value === void 0) continue;
620
+ row[key] = value;
621
+ }
622
+ return row;
623
+ }
624
+ /**
625
+ * Row access for the device fleet. Every method is a single statement against
626
+ * `device-manager:devices` — there is no in-memory copy of the fleet here and
627
+ * no cache: a per-device question is a primary-key lookup, a fleet question is
628
+ * one indexed scan.
629
+ */
630
+ var DeviceRowStore = class {
631
+ backend;
632
+ logger;
633
+ observer;
634
+ declared = null;
635
+ /** Call-site attribution for fleet reads. Armed only by
636
+ * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
637
+ census;
638
+ /**
639
+ * Is the fleet-read census armed right now? Exposed so a caller ABOVE this
640
+ * store (`device-queries.ts`) can skip extracting a caller identity off its
641
+ * input entirely when nobody is measuring — "the boolean field read first"
642
+ * pattern this repo already uses elsewhere to keep a diagnostic seam at
643
+ * zero cost while disarmed.
644
+ */
645
+ get censusArmed() {
646
+ return this.census.armed;
647
+ }
648
+ constructor(backend, logger, census, observer) {
649
+ this.backend = backend;
650
+ this.logger = logger;
651
+ this.observer = observer;
652
+ this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
653
+ if (this.census.armed) {
654
+ const startedAt = Date.now();
655
+ setTimeout(() => this.census.report(this.logger, Date.now() - startedAt), this.census.windowMs).unref?.();
656
+ }
657
+ }
658
+ /**
659
+ * Lazy, idempotent `declareCollection`, memoised on the PROMISE so N
660
+ * concurrent first-callers issue one declaration rather than N. A rejection
661
+ * is not latched — the slot is cleared so the next caller retries instead of
662
+ * inheriting a dead collection forever.
663
+ */
664
+ async declare() {
665
+ const existing = this.declared;
666
+ if (existing !== null) return existing;
667
+ const run = (async () => {
668
+ try {
669
+ await this.backend.declareCollection({
670
+ collection: DEVICE_ROWS_COLLECTION,
671
+ columns: DEVICE_ROWS_COLUMNS,
672
+ indexes: DEVICE_ROWS_INDEXES
673
+ });
674
+ } catch (err) {
675
+ this.declared = null;
676
+ throw err;
677
+ }
678
+ })();
679
+ this.declared = run;
680
+ return run;
681
+ }
682
+ /** One device, by numeric id. `null` when the fleet does not know it. */
683
+ async get(deviceId) {
684
+ await this.declare();
685
+ const raw = await this.backend.get({
686
+ collection: DEVICE_ROWS_COLLECTION,
687
+ key: String(deviceId)
688
+ });
689
+ if (!isPlainObject(raw)) return null;
690
+ const decoded = decodeDeviceRow(raw);
691
+ if (decoded === null) {
692
+ this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
693
+ return null;
694
+ }
695
+ return decoded;
696
+ }
697
+ /**
698
+ * Every device, ordered by numeric id.
699
+ *
700
+ * `callerAddonId`, when known, is the addon that ORIGINATED this call —
701
+ * captured off the cap-channel envelope (`CapCallInput.callerAddonId`, set
702
+ * by `LocalChildRegistry` from the registered `childId`), never guessed.
703
+ * Passed straight to the census; a stack walk can never name it (see
704
+ * `fleet-read-census.ts#siteOf`).
705
+ */
706
+ async listAll(callerAddonId) {
707
+ return this.list({
708
+ orderBy: {
709
+ field: "deviceId",
710
+ direction: "asc"
711
+ },
712
+ limit: DEVICE_ROWS_FLEET_LIMIT
713
+ }, void 0, callerAddonId);
714
+ }
715
+ /**
716
+ * The fleet, read as narrowly as the question allows.
717
+ *
718
+ * `listAll` is a full-table `SELECT … ORDER BY "deviceId"` — ~1 017 rows a
719
+ * call on the live hub, 14–54 calls a minute — and its callers then filtered
720
+ * the result in JS. The two filters that CAN be pushed down are here:
721
+ *
722
+ * - `deviceIds` becomes a `whereIn`. The viewer's linked-devices panel asks
723
+ * about ~8 named ids; it was answered by reading the whole ledger. An
724
+ * EMPTY set reads nothing at all rather than degrading to "everything" —
725
+ * a request for no devices is a request, not an omission.
726
+ * - `slim` becomes a column projection, {@link DEVICE_ROWS_SLIM_COLUMNS}.
727
+ *
728
+ * `isCamera` is deliberately NOT one of them — see that constant's note and
729
+ * `device-row-store-filtered.spec.ts`.
730
+ *
731
+ * `callerAddonId` — see {@link listAll}'s doc; same meaning here.
732
+ */
733
+ async listFleet(opts, callerAddonId) {
734
+ if (opts.deviceIds !== void 0 && opts.deviceIds.length === 0) return [];
735
+ return this.list({
736
+ ...opts.deviceIds !== void 0 ? { whereIn: { deviceId: [...new Set(opts.deviceIds)] } } : {},
737
+ orderBy: {
738
+ field: "deviceId",
739
+ direction: "asc"
740
+ },
741
+ limit: DEVICE_ROWS_FLEET_LIMIT
742
+ }, opts.slim === true ? DEVICE_ROWS_SLIM_COLUMNS : void 0, callerAddonId);
743
+ }
744
+ /**
745
+ * Many devices, by numeric id, in ONE query.
746
+ *
747
+ * `get(id)` called once per id in a loop is the primary-key lookup this
748
+ * store exists to make cheap, repeated until it isn't — measured on the
749
+ * live hub 2026-08-25: `get device-manager:devices` at 1 656 calls/min
750
+ * steady-state and 17 687 during boot, exactly one row per call. This
751
+ * collapses that into the same `whereIn` {@link listFleet} already does for
752
+ * a fleet read, keyed by id.
753
+ *
754
+ * A requested id the fleet does not know is simply ABSENT from the map —
755
+ * never a fabricated row, matching {@link get}'s `null`. An empty `ids`
756
+ * reads nothing at all, same as `listFleet({ deviceIds: [] })`.
757
+ */
758
+ async getMany(ids) {
759
+ const rows = await this.listFleet({ deviceIds: ids });
760
+ return new Map(rows.map((row) => [row.meta.id, row]));
761
+ }
762
+ /**
763
+ * The device an addon knows as `stableId`, or `null`.
764
+ *
765
+ * `(addonId, stableId)` is the addon-facing identity — unique by
766
+ * construction, since `allocateDeviceId` is the only thing that mints a row
767
+ * and it returns the existing id for a pair it already knows. A second row
768
+ * for the pair would be a corruption, so this takes the LOWEST id and says
769
+ * so rather than picking arbitrarily.
770
+ */
771
+ async findByStableId(addonId, stableId) {
772
+ const rows = await this.list({
773
+ where: {
774
+ addonId,
775
+ stableId
776
+ },
777
+ orderBy: {
778
+ field: "deviceId",
779
+ direction: "asc"
780
+ },
781
+ limit: 2
782
+ });
783
+ const first = rows[0];
784
+ if (first === void 0) return null;
785
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one (addonId, stableId) — using the lowest id", {
786
+ tags: { deviceId: first.meta.id },
787
+ meta: {
788
+ addonId,
789
+ stableId,
790
+ ids: rows.map((r) => r.meta.id)
791
+ }
792
+ });
793
+ return first;
794
+ }
795
+ /**
796
+ * The device that owns a template alias, or `null`. Aliases are unique, so a
797
+ * second row for one alias would be a corruption: the LOWEST id is answered and
798
+ * the duplicate is said on the record.
799
+ */
800
+ async findByAlias(alias) {
801
+ const rows = await this.list({
802
+ where: { alias },
803
+ orderBy: {
804
+ field: "deviceId",
805
+ direction: "asc"
806
+ },
807
+ limit: 2
808
+ });
809
+ const first = rows[0];
810
+ if (first === void 0) return null;
811
+ if (rows.length > 1) this.logger.warn("duplicate device rows for one alias — using the lowest id", {
812
+ tags: { deviceId: first.meta.id },
813
+ meta: {
814
+ alias,
815
+ ids: rows.map((r) => r.meta.id)
816
+ }
817
+ });
818
+ return first;
819
+ }
820
+ /** Every device owned by one addon, ordered by numeric id. */
821
+ async listByAddon(addonId) {
822
+ return this.list({
823
+ where: { addonId },
824
+ orderBy: {
825
+ field: "deviceId",
826
+ direction: "asc"
827
+ },
828
+ limit: DEVICE_ROWS_FLEET_LIMIT
829
+ });
830
+ }
831
+ /** Every device an integration owns, ordered by numeric id. */
832
+ async listByIntegration(integrationId) {
833
+ return this.list({
834
+ where: { integrationId },
835
+ orderBy: {
836
+ field: "deviceId",
837
+ direction: "asc"
838
+ },
839
+ limit: DEVICE_ROWS_FLEET_LIMIT
840
+ });
841
+ }
842
+ /** Direct children of one device, ordered by numeric id. */
843
+ async listByParent(parentDeviceId) {
844
+ return this.list({
845
+ where: { parentDeviceId },
846
+ orderBy: {
847
+ field: "deviceId",
848
+ direction: "asc"
849
+ },
850
+ limit: DEVICE_ROWS_FLEET_LIMIT
851
+ });
852
+ }
853
+ /**
854
+ * Direct children of MANY devices, in ONE query.
855
+ *
856
+ * `listByParent` called once per parent is the same shape `get` was before
857
+ * {@link getMany}: an indexed lookup this store makes cheap, repeated until
858
+ * it isn't. Measured on the live hub 2026-08-27, 120-second boot window:
859
+ * `DeviceRowStore.list < DeviceRowStore.listByParent < getChildren` at
860
+ * **1 024 calls** — one per device — for 919 rows in total. The BFS in
861
+ * `device-meta-actions.ts#collectDescendants` walked a container tree the
862
+ * same way, one query per node.
863
+ *
864
+ * `whereIn` on the indexed `parentDeviceId` column collapses a level of that
865
+ * walk into a single statement. Contract, verbatim from {@link getMany}: an
866
+ * EMPTY `parentDeviceIds` reads nothing at all rather than degrading to
867
+ * "everything", and a parent with no children — or one the fleet does not
868
+ * know — is simply ABSENT from the map, never an invented empty row.
869
+ */
870
+ async listByParentMany(parentDeviceIds) {
871
+ const out = /* @__PURE__ */ new Map();
872
+ const unique = [...new Set(parentDeviceIds)];
873
+ if (unique.length === 0) return out;
874
+ const rows = await this.list({
875
+ whereIn: { parentDeviceId: unique },
876
+ orderBy: {
877
+ field: "deviceId",
878
+ direction: "asc"
879
+ },
880
+ limit: DEVICE_ROWS_FLEET_LIMIT
881
+ });
882
+ const byParent = /* @__PURE__ */ new Map();
883
+ for (const row of rows) {
884
+ const parent = row.meta.parentDeviceId;
885
+ if (parent === null || parent === void 0) continue;
886
+ const bucket = byParent.get(parent);
887
+ if (bucket === void 0) byParent.set(parent, [row]);
888
+ else bucket.push(row);
889
+ }
890
+ for (const [parent, bucket] of byParent) out.set(parent, bucket);
891
+ return out;
892
+ }
893
+ /** How many devices the fleet holds. Used to tell "empty store" from "gone device". */
894
+ async count() {
895
+ await this.declare();
896
+ return this.backend.count({ collection: DEVICE_ROWS_COLLECTION });
897
+ }
898
+ async list(filter, columns, callerAddonId) {
899
+ const site = this.census.siteOf(callerAddonId);
900
+ await this.declare();
901
+ const records = await this.backend.query({
902
+ collection: DEVICE_ROWS_COLLECTION,
903
+ filter,
904
+ ...columns === void 0 ? {} : { columns }
905
+ });
906
+ this.census.record(site, records.length);
907
+ const out = [];
908
+ for (const record of records) {
909
+ const decoded = decodeDeviceRow(record.data);
910
+ if (decoded === null) {
911
+ this.logger.warn("device row skipped — identity fields missing", { meta: { rowId: record.id } });
912
+ continue;
913
+ }
914
+ out.push(decoded);
915
+ }
916
+ return out;
917
+ }
918
+ /** Insert or replace the whole identity row. */
919
+ async upsert(meta, extra = {}) {
920
+ await this.declare();
921
+ await this.backend.set({
922
+ collection: DEVICE_ROWS_COLLECTION,
923
+ key: String(meta.id),
924
+ value: encodeDeviceRow(meta, extra)
925
+ });
926
+ this.observer?.rowWritten(meta);
927
+ }
928
+ /**
929
+ * Write the named columns of an EXISTING row and nothing else.
930
+ *
931
+ * An UPDATE, deliberately not an upsert: a partial upsert would try to INSERT
932
+ * a row carrying only the patched columns, and SQLite rejects that on the
933
+ * `NOT NULL` identity columns before the primary-key conflict can turn it
934
+ * into an update. Every caller resolves the row under the write lock and
935
+ * throws when it is gone, so matching zero rows means a device was removed
936
+ * between the resolve and the write — the patch is lost, and a lost write
937
+ * that says nothing reads as a write that happened.
938
+ */
939
+ async patch(deviceId, patch) {
940
+ const columns = encodeDeviceRowPatch(patch);
941
+ if (Object.keys(columns).length === 0) return;
942
+ await this.declare();
943
+ const { updated } = await this.backend.updateWhere({
944
+ collection: DEVICE_ROWS_COLLECTION,
945
+ filter: { where: { id: String(deviceId) } },
946
+ data: columns
947
+ });
948
+ if (updated === 0) {
949
+ this.logger.warn("device row patch matched no row — the device was removed under it", {
950
+ tags: { deviceId },
951
+ meta: { columns: Object.keys(columns) }
952
+ });
953
+ return;
954
+ }
955
+ this.observer?.rowPatched(deviceId, patch);
956
+ }
957
+ /**
958
+ * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
959
+ * for why this is a separate, fully-specified statement rather than a patch.
960
+ */
961
+ async upsertRegistration(row) {
962
+ await this.declare();
963
+ await this.backend.set({
964
+ collection: DEVICE_ROWS_COLLECTION,
965
+ key: String(row.deviceId),
966
+ value: {
967
+ deviceId: row.deviceId,
968
+ addonId: row.addonId,
969
+ stableId: row.stableId,
970
+ type: row.type,
971
+ name: row.name,
972
+ userNamed: row.userNamed,
973
+ location: row.location,
974
+ disabled: row.disabled,
975
+ parentDeviceId: row.parentDeviceId,
976
+ registered: row.registered,
977
+ features: [...row.features],
978
+ exportFingerprint: row.exportFingerprint
979
+ }
980
+ });
981
+ this.observer?.registrationWritten(row);
982
+ }
983
+ /** Drop the device's row. Idempotent. */
984
+ /**
985
+ * Exchange the ids of two devices, carrying their children with them.
986
+ *
987
+ * ## Why this exists as a primitive
988
+ *
989
+ * Replacing a camera means the new hardware has to become the device the rest
990
+ * of the system already knows. Everything general about a camera is keyed on
991
+ * the NUMERIC id and on nothing else — the recording path on disk is
992
+ * `<deviceId>/profile/…`, the hour ledger, the media store and zone ownership
993
+ * carry `deviceId` and not one `stableId` between them, and all four
994
+ * ecosystem exports (Home Assistant, Alexa, HomeKit, Google) key on it too.
995
+ * Moving that work is the expensive, lossy operation. Moving the NUMBER is
996
+ * two rows.
997
+ *
998
+ * ## Children are re-pointed, not renumbered
999
+ *
1000
+ * A child keeps its own id and follows its parent: every row whose
1001
+ * `parentDeviceId` was `a` now names `b`, and the reverse. Renumbering the
1002
+ * children as well would move THEIR general work for no reason — the
1003
+ * accessory's own recordings and rules are keyed on the child id, which is
1004
+ * not the id being inherited.
1005
+ *
1006
+ * ## There are no transactions here, so the ORDER is the safety
1007
+ *
1008
+ * The backing store is a collection API (`set` / `delete` / `updateWhere`);
1009
+ * there is no rollback to lean on. So the sequence is chosen to make every
1010
+ * crash point LOUD rather than plausible: `a` first moves to a freshly
1011
+ * allocated id, which the monotonic counter guarantees was never used and
1012
+ * will never be reused. A crash before the end therefore leaves a device
1013
+ * missing from its number and a stray at an unfamiliar one — visible in the
1014
+ * device list at a glance. What it can never leave is two rows on one number,
1015
+ * or a row that looks correct while its children point elsewhere.
1016
+ *
1017
+ * The caller holds {@link DeviceMetaStore.withMetaWriteLock}. This method does
1018
+ * not take it: taking it here would deadlock the migration that has to disable
1019
+ * functions on both devices in the same critical section.
1020
+ */
1021
+ async swapIds(a, b, tempId) {
1022
+ const { rowA, rowB, childrenOfA, childrenOfB } = await this.planSwap(a, b, tempId).catch((err) => {
1023
+ if (err instanceof MigrationRefusedError) throw err;
1024
+ throw new MigrationRefusedError(`[device-manager] swapIds: precheck failed before any row moved — ${err instanceof Error ? err.message : String(err)}`, { cause: err });
1025
+ });
1026
+ await this.moveRow(rowA, tempId);
1027
+ await this.moveRow(rowB, a);
1028
+ await this.moveRow({
1029
+ ...rowA,
1030
+ meta: {
1031
+ ...rowA.meta,
1032
+ id: tempId
1033
+ }
1034
+ }, b);
1035
+ for (const childId of childrenOfA) await this.patch(childId, { parentDeviceId: b });
1036
+ for (const childId of childrenOfB) await this.patch(childId, { parentDeviceId: a });
1037
+ this.logger.info("device ids swapped", {
1038
+ tags: { deviceId: a },
1039
+ meta: {
1040
+ a,
1041
+ b,
1042
+ childrenOfA,
1043
+ childrenOfB
1044
+ }
1045
+ });
1046
+ }
1047
+ /** The read-only half of {@link swapIds}: every refusal, every read, no write. */
1048
+ async planSwap(a, b, tempId) {
1049
+ if (a === b) throw new MigrationRefusedError(`[device-manager] swapIds: ${a} and ${b} are the same device`);
1050
+ await this.declare();
1051
+ const rowA = await this.get(a);
1052
+ const rowB = await this.get(b);
1053
+ if (rowA === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${a} does not exist`);
1054
+ if (rowB === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${b} does not exist`);
1055
+ if (await this.get(tempId) !== null) throw new MigrationRefusedError(`[device-manager] swapIds: temp id ${tempId} is taken`);
1056
+ return {
1057
+ rowA,
1058
+ rowB,
1059
+ childrenOfA: (await this.listByParent(a)).map((r) => r.meta.id),
1060
+ childrenOfB: (await this.listByParent(b)).map((r) => r.meta.id)
1061
+ };
1062
+ }
1063
+ /** Rewrite a row under a new id and drop the old key. Not exported: the only
1064
+ * legitimate reason to move a row is {@link swapIds}. */
1065
+ async moveRow(row, toId) {
1066
+ await this.upsert({
1067
+ ...row.meta,
1068
+ id: toId
1069
+ }, {
1070
+ registered: row.registered,
1071
+ metadata: row.metadata
1072
+ });
1073
+ await this.remove(row.meta.id);
1074
+ }
1075
+ async remove(deviceId) {
1076
+ await this.declare();
1077
+ await this.backend.delete({
1078
+ collection: DEVICE_ROWS_COLLECTION,
1079
+ key: String(deviceId)
1080
+ });
1081
+ this.observer?.rowRemoved(deviceId);
1082
+ }
1083
+ /**
1084
+ * The retirement door for the three blobs this collection replaced.
1085
+ *
1086
+ * The purge is gated on THIS collection being non-empty, and the count has to
1087
+ * be taken after `declare()` — which is why the owning addon runs it and the
1088
+ * settings engine cannot: at the engine's own boot no addon has declared
1089
+ * anything, so every successor would read as unreadable, forever.
1090
+ */
1091
+ retiredRowStore() {
1092
+ return {
1093
+ hasRow: async (spec) => {
1094
+ const raw = await this.backend.get({
1095
+ collection: spec.collection,
1096
+ key: spec.row
1097
+ });
1098
+ return raw !== void 0 && raw !== null;
1099
+ },
1100
+ deleteRow: async (spec) => {
1101
+ await this.backend.delete({
1102
+ collection: spec.collection,
1103
+ key: spec.row
1104
+ });
1105
+ },
1106
+ countRows: async (collection) => {
1107
+ await this.declare();
1108
+ return this.backend.count({ collection });
1109
+ }
1110
+ };
1111
+ }
1112
+ };
1113
+ //#endregion
1114
+ Object.defineProperty(exports, "DEVICE_ROWS_COLLECTION", {
1115
+ enumerable: true,
1116
+ get: function() {
1117
+ return DEVICE_ROWS_COLLECTION;
1118
+ }
1119
+ });
1120
+ Object.defineProperty(exports, "DeviceRowStore", {
1121
+ enumerable: true,
1122
+ get: function() {
1123
+ return DeviceRowStore;
1124
+ }
1125
+ });
1126
+ Object.defineProperty(exports, "MigrationRefusedError", {
1127
+ enumerable: true,
1128
+ get: function() {
1129
+ return MigrationRefusedError;
1130
+ }
1131
+ });
1132
+ Object.defineProperty(exports, "deviceManagerRecordKinds", {
1133
+ enumerable: true,
1134
+ get: function() {
1135
+ return deviceManagerRecordKinds;
1136
+ }
1137
+ });
1138
+ Object.defineProperty(exports, "deviceRowBackendOf", {
1139
+ enumerable: true,
1140
+ get: function() {
1141
+ return deviceRowBackendOf;
1142
+ }
1143
+ });