@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
@@ -3,13 +3,14 @@ Object.defineProperties(exports, {
3
3
  [Symbol.toStringTag]: { value: "Module" }
4
4
  });
5
5
  const require_chunk = require("../../chunk-Cek0wNdY.js");
6
- const require_dist = require("../../dist-BvoilCmO.js");
6
+ const require_dist = require("../../dist-CxIM-RDP.js");
7
7
  const require_read_all_rows$1 = require("../../read-all-rows-CVoO1ONM.js");
8
8
  const require_log_redactor = require("../../log-redactor-BhIEMaG9.js");
9
- const require_rename_composition_block = require("../../rename-composition-block-CMP2cY6o.js");
9
+ const require_rename_composition_block = require("../../rename-composition-block-Cr_M-06e.js");
10
10
  const require_prefix_range = require("../../prefix-range-D_KueXbQ.js");
11
11
  const require_prefix_walk = require("../../prefix-walk-Dv6MLZlM.js");
12
12
  const require_retired_settings_keys = require("../../retired-settings-keys-C8nOOr5H.js");
13
+ const require_device_row_store = require("../../device-row-store-DMKWs6YZ.js");
13
14
  const require_template_protocol = require("../../template-protocol-D5ogm1rj.js");
14
15
  const require_dns_wire = require("../../dns-wire-B1BvF9Ao.js");
15
16
  let zod = require("zod");
@@ -2622,14 +2623,14 @@ function buildRecordingOnboardConfigSchema(options, status) {
2622
2623
  ]
2623
2624
  }] };
2624
2625
  }
2625
- function readBoolean$1(patch, key) {
2626
+ function readBoolean(patch, key) {
2626
2627
  if (!(key in patch)) return void 0;
2627
2628
  const value = patch[key];
2628
2629
  if (typeof value === "boolean") return value;
2629
2630
  if (value === "true") return true;
2630
2631
  if (value === "false") return false;
2631
2632
  }
2632
- function readNumber$1(patch, key) {
2633
+ function readNumber(patch, key) {
2633
2634
  if (!(key in patch)) return void 0;
2634
2635
  const value = Number(patch[key]);
2635
2636
  return Number.isFinite(value) ? value : void 0;
@@ -2678,15 +2679,15 @@ function readWindowRow(row) {
2678
2679
  */
2679
2680
  function parseRecordingOnboardFormPatch(patch) {
2680
2681
  const out = {};
2681
- const enabled = readBoolean$1(patch, RECORDING_ONBOARD_KEYS.enabled);
2682
+ const enabled = readBoolean(patch, RECORDING_ONBOARD_KEYS.enabled);
2682
2683
  if (enabled !== void 0) out.enabled = enabled;
2683
- const overwrite = readBoolean$1(patch, RECORDING_ONBOARD_KEYS.overwriteWhenFull);
2684
+ const overwrite = readBoolean(patch, RECORDING_ONBOARD_KEYS.overwriteWhenFull);
2684
2685
  if (overwrite !== void 0) out.overwriteWhenFull = overwrite;
2685
- const pre = readNumber$1(patch, RECORDING_ONBOARD_KEYS.preRecordSec);
2686
+ const pre = readNumber(patch, RECORDING_ONBOARD_KEYS.preRecordSec);
2686
2687
  if (pre !== void 0) out.preRecordSec = pre;
2687
- const post = readNumber$1(patch, RECORDING_ONBOARD_KEYS.postRecordSec);
2688
+ const post = readNumber(patch, RECORDING_ONBOARD_KEYS.postRecordSec);
2688
2689
  if (post !== void 0) out.postRecordSec = post;
2689
- const segment = readNumber$1(patch, RECORDING_ONBOARD_KEYS.segmentMinutes);
2690
+ const segment = readNumber(patch, RECORDING_ONBOARD_KEYS.segmentMinutes);
2690
2691
  if (segment !== void 0) out.segmentMinutes = segment;
2691
2692
  if (RECORDING_ONBOARD_KEYS.windows in patch) {
2692
2693
  const raw = patch[RECORDING_ONBOARD_KEYS.windows];
@@ -6540,34 +6541,6 @@ async function runLocationBackfillAtBoot(pctx, bootRows) {
6540
6541
  }
6541
6542
  });
6542
6543
  }
6543
- //#endregion
6544
- //#region src/builtins/device-manager/migration-refused.ts
6545
- /**
6546
- * A migration step that REFUSED with nothing moved.
6547
- *
6548
- * `migrateDevice` distinguishes two kinds of failure after the disable phase,
6549
- * and they must never be confused (D663 task 5b ruling I-1):
6550
- *
6551
- * - **refused, nothing moved** — a precheck of `swapIds` (a row missing, the
6552
- * temp id taken), the mirror drain that runs before the rows move, or a
6553
- * claim found in the mirror after that drain (it landed while the migration
6554
- * was starting). Both cameras are switched back to exactly what they were,
6555
- * because nothing about either device changed.
6556
- * - **failed while moving** — any other throw from `swapIds` (rows partially
6557
- * moved), or from `swapHardwareState` (rows swapped, state not). The two
6558
- * devices may wear each other's identity; switching them back on would run
6559
- * pipelines against crossed identities, so they stay off and the operator is
6560
- * told to intervene.
6561
- *
6562
- * Only a step that KNOWS it wrote nothing may throw this. An unknown error is
6563
- * read as "may have moved" — the safe reading.
6564
- */
6565
- var MigrationRefusedError = class extends Error {
6566
- constructor(message, options) {
6567
- super(message, options);
6568
- this.name = "MigrationRefusedError";
6569
- }
6570
- };
6571
6544
  /** A refusal that names a switch the camera does not offer, rather than one it
6572
6545
  * could not be asked about. The cap documents rejecting the former; anything
6573
6546
  * else is treated as the camera being out of reach, which is the safe reading:
@@ -6727,7 +6700,7 @@ async function migrateDevice$1(deps, input) {
6727
6700
  try {
6728
6701
  await deps.swapIds(sourceId, targetId);
6729
6702
  } catch (err) {
6730
- if (err instanceof MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
6703
+ if (err instanceof require_device_row_store.MigrationRefusedError) return rollBackRefusal(deps, ids, prior, err);
6731
6704
  alarmPartialMigration(deps, ids, "swapIds", err);
6732
6705
  throw err;
6733
6706
  }
@@ -6839,7 +6812,7 @@ var FieldClaimsBlockMigrationError = class extends Error {
6839
6812
  * moved — so it is a {@link MigrationRefusedError}: both cameras' switches are
6840
6813
  * restored, and the claim stays on the number it names.
6841
6814
  */
6842
- var ClaimLandedDuringMigrationError = class extends MigrationRefusedError {
6815
+ var ClaimLandedDuringMigrationError = class extends require_device_row_store.MigrationRefusedError {
6843
6816
  sourceId;
6844
6817
  targetId;
6845
6818
  blocked;
@@ -9232,60 +9205,8 @@ var IdentityLinkReconciler = class {
9232
9205
  }
9233
9206
  };
9234
9207
  //#endregion
9235
- //#region src/builtins/device-manager/record-kinds.ts
9236
- var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
9237
- var DeviceTombstoneBodySchema = require_dist.DeviceTombstoneSchema.omit({ deviceId: true });
9238
- var _deviceManagerRecordKinds = require_dist.defineRecordKinds({
9239
- tombstones: {
9240
- schema: DeviceTombstoneBodySchema,
9241
- class: "ledger",
9242
- writeTrigger: "`removeDevice` records one row per deleted device after the device row is gone; re-record keeps the earlier `deletedAt`",
9243
- device: "none",
9244
- at: "required",
9245
- indexes: [{
9246
- name: "deleted_at",
9247
- fields: ["deletedAt"]
9248
- }],
9249
- retention: {
9250
- owner: "device-manager",
9251
- reason: "90 days (`DEVICE_TOMBSTONE_RETENTION_MS`), pruned whenever a tombstone is written or the list is read"
9252
- }
9253
- },
9254
- "discovery-proposals": {
9255
- schema: require_dist.DiscoveryProposalBodySchema,
9256
- class: "config",
9257
- writeTrigger: "the passive listener and the 30-minute sweep of `local-network` re-see a device (`lastSeenAt` and `at` move); `dismissDiscoveryProposal` sets `dismissed`",
9258
- device: "none",
9259
- at: "required",
9260
- indexes: [{
9261
- name: "last_seen_at",
9262
- fields: ["lastSeenAt"]
9263
- }],
9264
- retention: {
9265
- ttlMs: 2160 * 60 * 60 * 1e3,
9266
- from: "at"
9267
- }
9268
- },
9269
- "identity-links": {
9270
- schema: require_dist.IdentityLinkBodySchema,
9271
- class: "config",
9272
- writeTrigger: "the identity-link reconciler sees a candidate appear, upgrade or lose its evidence; the operator confirms, dismisses or unlinks (D1063)",
9273
- device: "none",
9274
- at: "none",
9275
- indexes: [{
9276
- name: "a_device",
9277
- fields: ["a.deviceId"]
9278
- }, {
9279
- name: "b_device",
9280
- fields: ["b.deviceId"]
9281
- }],
9282
- retention: { none: "a link lives as long as both its devices; a dismissal is sticky (operator intent)" }
9283
- }
9284
- });
9285
- var deviceManagerRecordKinds = _deviceManagerRecordKinds;
9286
- _deviceManagerRecordKinds.tombstones;
9287
- //#endregion
9288
9208
  //#region src/builtins/device-manager/identity-links-store.ts
9209
+ var import_read_all_rows = require_read_all_rows$1.require_read_all_rows();
9289
9210
  var IdentityLinksStore = class IdentityLinksStore {
9290
9211
  kind;
9291
9212
  links = null;
@@ -9293,7 +9214,7 @@ var IdentityLinksStore = class IdentityLinksStore {
9293
9214
  this.kind = kind;
9294
9215
  }
9295
9216
  static of(records) {
9296
- return new IdentityLinksStore(records.kind(deviceManagerRecordKinds["identity-links"]));
9217
+ return new IdentityLinksStore(records.kind(require_device_row_store.deviceManagerRecordKinds["identity-links"]));
9297
9218
  }
9298
9219
  async load() {
9299
9220
  const rows = await (0, import_read_all_rows.readAllRows)(this.kind);
@@ -10625,7 +10546,7 @@ var DeviceTombstoneStore = class DeviceTombstoneStore {
10625
10546
  }
10626
10547
  static of(records, logger) {
10627
10548
  return new DeviceTombstoneStore({
10628
- kind: records.kind(deviceManagerRecordKinds.tombstones),
10549
+ kind: records.kind(require_device_row_store.deviceManagerRecordKinds.tombstones),
10629
10550
  logger
10630
10551
  });
10631
10552
  }
@@ -10788,7 +10709,7 @@ var DiscoveryProposalStore = class DiscoveryProposalStore {
10788
10709
  this.now = now;
10789
10710
  }
10790
10711
  static of(records, now) {
10791
- return new DiscoveryProposalStore(records.kind(deviceManagerRecordKinds["discovery-proposals"]), now);
10712
+ return new DiscoveryProposalStore(records.kind(require_device_row_store.deviceManagerRecordKinds["discovery-proposals"]), now);
10792
10713
  }
10793
10714
  /** Record what a provider classified. Returns how many proposals are NEW. */
10794
10715
  async observe(addonId, candidates) {
@@ -10844,1040 +10765,6 @@ var DiscoveryProposalStore = class DiscoveryProposalStore {
10844
10765
  }
10845
10766
  };
10846
10767
  //#endregion
10847
- //#region src/builtins/device-manager/fleet-read-census.ts
10848
- /** How many stack frames identify a call site. One frame is a method; three are
10849
- * a cause — `listFleet < listAll < onDeviceRegistered` is the answer, `listAll`
10850
- * alone is not. Same choice, for the same reason, as `read-census.ts`. */
10851
- var CENSUS_STACK_FRAMES = 3;
10852
- function siteFromStack(stack) {
10853
- if (stack === void 0) return "unknown";
10854
- 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) => {
10855
- const open = line.indexOf(" (");
10856
- return (open > 0 ? line.slice(0, open) : line).replace(/^async\s+/, "");
10857
- });
10858
- return frames.length === 0 ? "unknown" : frames.join(" < ");
10859
- }
10860
- var FleetReadCensus = class FleetReadCensus {
10861
- /**
10862
- * Longest window the census may be armed for.
10863
- *
10864
- * Ten minutes covers a boot several times over and bounds what an operator
10865
- * pays if they set the variable and forget it. A diagnostic that can be left
10866
- * on becomes a tax nobody remembers enabling.
10867
- */
10868
- static MAX_WINDOW_MS = 10 * 6e4;
10869
- windowMs;
10870
- closesAt;
10871
- counts = /* @__PURE__ */ new Map();
10872
- reported = false;
10873
- constructor(rawEnv, nowMs) {
10874
- const parsed = rawEnv === void 0 ? NaN : Number(rawEnv);
10875
- const valid = Number.isFinite(parsed) && parsed > 0;
10876
- this.windowMs = valid ? Math.min(parsed, FleetReadCensus.MAX_WINDOW_MS) : 0;
10877
- this.closesAt = valid ? nowMs + this.windowMs : 0;
10878
- }
10879
- get armed() {
10880
- return this.windowMs > 0;
10881
- }
10882
- /** Test seam: pretend the window closed. Production reads the clock. */
10883
- closeAt(nowMs) {
10884
- if (nowMs >= this.closesAt) this.forceClosed = true;
10885
- }
10886
- forceClosed = false;
10887
- isOpen(nowMs) {
10888
- if (!this.armed || this.forceClosed) return false;
10889
- return nowMs < this.closesAt;
10890
- }
10891
- /**
10892
- * Capture the caller, or `null` when the window is shut.
10893
- *
10894
- * Called at the START of a read. A read that began inside the window belongs
10895
- * to it even if it lands after the close — otherwise the slow reads at the
10896
- * edge would be attributed to nobody, and the slow ones are the interesting
10897
- * ones.
10898
- *
10899
- * `callerAddonId`, when given, is formatted as the site VERBATIM instead of
10900
- * walking the local stack. A call that arrived over the cap channel — a
10901
- * forked addon's `ctx.api.deviceManager.listAll.query()`, routed through
10902
- * `LocalChildRegistry` → `onUnownedCall` → `CapRouteResolver` — carries its
10903
- * origin as DATA (the registered `childId` the parent captured off the UDS
10904
- * connection), and no amount of stack depth would ever recover it: every
10905
- * frame between the socket read and this call is the SAME generic
10906
- * dispatcher code (`onUnownedCall`, `dispatch`, `invoke`) regardless of
10907
- * which addon called — the 2026-08-25 boot census measured this directly,
10908
- * five thousand calls landing on `listAll` with nothing nameable above it.
10909
- *
10910
- * `isOpen` is checked FIRST, before the id is even looked at — a caller
10911
- * threading a (cheap, already-known) `callerAddonId` through on every
10912
- * request, armed or not, must not pay for the template string when
10913
- * disarmed. This is also why formatting lives HERE rather than at the call
10914
- * site: `DeviceRowStore` passes the raw id through unconditionally, and
10915
- * only this method — which already knows whether armed — decides whether
10916
- * to spend anything on it.
10917
- */
10918
- siteOf(callerAddonId, nowMs = Date.now()) {
10919
- if (!this.isOpen(nowMs)) return null;
10920
- if (callerAddonId !== void 0) return `addon:${callerAddonId}`;
10921
- const holder = {};
10922
- Error.captureStackTrace(holder, this.siteOf);
10923
- return siteFromStack(holder.stack);
10924
- }
10925
- /** Count one read at an already-captured site. A `null` site is not counted. */
10926
- record(site, rowCount) {
10927
- if (site === null) return;
10928
- const existing = this.counts.get(site);
10929
- if (existing === void 0) {
10930
- this.counts.set(site, {
10931
- site,
10932
- calls: 1,
10933
- rows: rowCount
10934
- });
10935
- return;
10936
- }
10937
- existing.calls += 1;
10938
- existing.rows += rowCount;
10939
- }
10940
- /** Attributed sites, busiest first. */
10941
- rows() {
10942
- return [...this.counts.values()].map((c) => ({
10943
- site: c.site,
10944
- calls: c.calls,
10945
- rows: c.rows
10946
- })).sort((a, b) => b.calls - a.calls);
10947
- }
10948
- /**
10949
- * Emit the report ONCE.
10950
- *
10951
- * `perMin` is included because the raw count is unreadable without the window
10952
- * it was taken over — "4 149" means nothing until you know it was 66 seconds.
10953
- */
10954
- report(logger, elapsedMs) {
10955
- if (this.reported || !this.armed) return;
10956
- this.reported = true;
10957
- const rows = this.rows();
10958
- const totalCalls = rows.reduce((acc, r) => acc + r.calls, 0);
10959
- logger.info("fleet read census", { meta: {
10960
- elapsedMs,
10961
- sites: rows.length,
10962
- totalCalls,
10963
- rows: rows.map((r) => ({
10964
- site: r.site,
10965
- calls: r.calls,
10966
- rows: r.rows,
10967
- perMin: elapsedMs === 0 ? 0 : Math.round(r.calls * 6e4 / elapsedMs)
10968
- }))
10969
- } });
10970
- }
10971
- };
10972
- //#endregion
10973
- //#region src/builtins/device-manager/device-row-store.ts
10974
- /**
10975
- * `device-manager:devices` — ONE ROW PER DEVICE.
10976
- *
10977
- * ## What this replaces
10978
- *
10979
- * The device-manager used to keep its whole fleet in three JSON blobs on the
10980
- * addon-settings row set (`deviceMeta`, `deviceMetadata`, `deviceIndex`).
10981
- * Measured on the live hub 2026-08-19: 467 KB + 87 KB + 70 KB = 625 KB of the
10982
- * table's 627 KB, and EVERY read of any of them read and `JSON.parse`d all
10983
- * three, synchronously, on hub-main's event loop — `ctx.settings.readAddonStore`
10984
- * lands in `SqliteSettingsBackend.getAllAddon`, which is prefix-scoped to the
10985
- * addon but not to the key. A V8 profile of that boot had hub-main's JS thread
10986
- * 99.9% busy for 76 s with 64% of it inside `getAllAddon`, ~89% of that entered
10987
- * through the meta store, and every runner's first store read queued behind it.
10988
- *
10989
- * Writing was worse than reading. `ConfigManager.createSettingsView`'s
10990
- * `writeAddonStore` is `setAllAddon(addonId, { ...existing, ...patch })`, and
10991
- * `setAllAddon` DELETEs and re-INSERTs every row of the addon — so renaming one
10992
- * camera rewrote 625 KB.
10993
- *
10994
- * A row per device makes the per-device question a primary-key lookup and the
10995
- * per-device write a single-row upsert touching only the columns named.
10996
- *
10997
- * ## Why `deviceIndex` has no column and no collection
10998
- *
10999
- * `deviceIndex` was `Record<addonId, stableId[]>` — pure derivation: `addonId`
11000
- * and `stableId` are fields of every row, so "this addon's devices" is
11001
- * `where: { addonId }`. It carried exactly one bit that is NOT derivable:
11002
- * membership meant "`registerDevice` has run at least once", which is how
11003
- * `registerDevice` tells a FIRST registration (emit `DeviceRegistered`) from a
11004
- * meta refresh. `allocateDeviceId` writes a row without registering, so row
11005
- * existence alone cannot answer it. That bit is the {@link registered} column,
11006
- * and nothing else of `deviceIndex` survives.
11007
- *
11008
- * ## Why metadata is a column and not a second collection
11009
- *
11010
- * `deviceMetadata` lived in its own blob for ONE reason: a blob write is
11011
- * whole-value, so a lifecycle writer (`registerDevice` / `setName` / …) that
11012
- * had to preserve a `metadata` field would eventually clobber a concurrent
11013
- * `setMetadata`. Single-writer-per-blob was the fix. Column writes have no such
11014
- * problem — `set` names its columns and leaves the rest of the row untouched —
11015
- * so the split has no reason to exist and metadata rides on the device's own
11016
- * row.
11017
- *
11018
- * ## Adding a column later
11019
- *
11020
- * `declareCollection` is additive ONLY when SQLite can `ALTER TABLE … ADD
11021
- * COLUMN` it. A new `NOT NULL` column without a `defaultValue` cannot be added
11022
- * to a populated table, so the backend counts it as non-additive and REBUILDS
11023
- * the collection — dropping every row. Any column added here after ship must
11024
- * either be nullable or carry a `defaultValue`.
11025
- */
11026
- /**
11027
- * @durable class=ledger owner=device-manager
11028
- * write="one row per device, written by `allocateDeviceId` (identity placeholder),
11029
- * `registerDevice` (full reconcile) and every meta setter (single-column patch);
11030
- * `setMetadata` patches the `metadata` column of the same row"
11031
- * retention="none — a row goes only when the operator removes the device
11032
- * (`removeDevice`), or when an integration is deleted and cascades. Bounded by the
11033
- * fleet an operator configures (974 rows on the reference hub)."
11034
- *
11035
- * ### Why `ledger` and not `config`
11036
- *
11037
- * This shipped as `class=registry`, a sixth class that does not exist —
11038
- * `DURABLE_CLASSES` is `ledger | mirror | ephemeral | config | audit`, so
11039
- * `check-durable-state-declared.ts` has failed since. `config` is the tempting
11040
- * answer, because a device's `name` and `location` ARE operator intent. It is
11041
- * the wrong one, and wrong in the dangerous direction: `config`'s rule is
11042
- * *"already durable everywhere"*, and that is exactly the premise that made the
11043
- * dead `devices` table look harmless right up to D183.
11044
- *
11045
- * Nothing else holds a device's NUMERIC id. `allocateDeviceId` mints it here
11046
- * and every other store in the system keys on it — `addon-device-settings`,
11047
- * `device-runtime-state`, every `pipeline-analytics:*` row, every recorder path.
11048
- * That is `ledger`'s definition verbatim ("a fact only this component ever
11049
- * held"), and `ledger`'s rule — *must not be pruned against a fallible read* —
11050
- * is precisely the rule this collection needs (D49): a `getBindings` or an
11051
- * integration listing that answers empty because it FAILED must never be
11052
- * allowed to retire a device row.
11053
- */
11054
- var DEVICE_ROWS_COLLECTION = "device-manager:devices";
11055
- /**
11056
- * Fleet reads pass this explicitly.
11057
- *
11058
- * `settings-store.query` applies a DEFAULT row cap of 2 000 when the caller
11059
- * names no `limit` (`query-bounds.ts`), and truncation there is silent to the
11060
- * caller — it warns in the engine's log and returns a short list that looks
11061
- * complete. The reference hub is already at 974 devices; half the default cap
11062
- * is not a margin worth betting the fleet listing on. 20 000 is the engine's
11063
- * hard ceiling, so this asks for everything the engine will ever serve in one
11064
- * call and any future need to page is a loud failure rather than a quiet one.
11065
- */
11066
- var DEVICE_ROWS_FLEET_LIMIT = 2e4;
11067
- var DEVICE_ROWS_COLUMNS = [
11068
- {
11069
- name: "id",
11070
- type: "TEXT",
11071
- primaryKey: true,
11072
- notNull: true
11073
- },
11074
- {
11075
- name: "deviceId",
11076
- type: "INTEGER",
11077
- notNull: true
11078
- },
11079
- {
11080
- name: "addonId",
11081
- type: "TEXT",
11082
- notNull: true
11083
- },
11084
- {
11085
- name: "stableId",
11086
- type: "TEXT",
11087
- notNull: true
11088
- },
11089
- {
11090
- name: "type",
11091
- type: "TEXT",
11092
- notNull: true
11093
- },
11094
- {
11095
- name: "name",
11096
- type: "TEXT",
11097
- notNull: true
11098
- },
11099
- {
11100
- name: "alias",
11101
- type: "TEXT"
11102
- },
11103
- {
11104
- name: "userNamed",
11105
- type: "BOOLEAN"
11106
- },
11107
- {
11108
- name: "location",
11109
- type: "TEXT"
11110
- },
11111
- {
11112
- name: "tags",
11113
- type: "JSON"
11114
- },
11115
- {
11116
- name: "disabled",
11117
- type: "BOOLEAN",
11118
- notNull: true,
11119
- defaultValue: false
11120
- },
11121
- {
11122
- name: "parentDeviceId",
11123
- type: "INTEGER"
11124
- },
11125
- {
11126
- name: "registered",
11127
- type: "BOOLEAN",
11128
- notNull: true,
11129
- defaultValue: false
11130
- },
11131
- {
11132
- name: "features",
11133
- type: "JSON"
11134
- },
11135
- {
11136
- name: "exportFingerprint",
11137
- type: "TEXT"
11138
- },
11139
- {
11140
- name: "integrationId",
11141
- type: "TEXT"
11142
- },
11143
- {
11144
- name: "linkDeviceId",
11145
- type: "INTEGER"
11146
- },
11147
- {
11148
- name: "primaryChildEntityId",
11149
- type: "TEXT"
11150
- },
11151
- {
11152
- name: "childLayout",
11153
- type: "JSON"
11154
- },
11155
- {
11156
- name: "primaryChildPreference",
11157
- type: "JSON"
11158
- },
11159
- {
11160
- name: "role",
11161
- type: "TEXT"
11162
- },
11163
- {
11164
- name: "display",
11165
- type: "JSON"
11166
- },
11167
- {
11168
- name: "metadata",
11169
- type: "JSON"
11170
- },
11171
- {
11172
- name: "identifiers",
11173
- type: "JSON"
11174
- },
11175
- {
11176
- name: "attachedIdentifiers",
11177
- type: "JSON"
11178
- },
11179
- {
11180
- name: "attachedRetained",
11181
- type: "JSON"
11182
- }
11183
- ];
11184
- /**
11185
- * The columns a SLIM fleet read selects: every declared column except the
11186
- * primary key (always returned) and `metadata`.
11187
- *
11188
- * ## Why this is a DENYLIST and must stay one
11189
- *
11190
- * `decodeDeviceRow` returns `null` when `deviceId`, `addonId`, `stableId`,
11191
- * `type` or `name` is missing, and `list()` then SKIPS the row with a warn. A
11192
- * hand-written allowlist that forgot one of the five would not make the fleet
11193
- * slower — it would make devices vanish from every listing, quietly, and the
11194
- * only trace would be a log line nobody is reading at the time. Deriving the
11195
- * list by subtraction means a column added tomorrow is carried by default and
11196
- * the only way to lose one is to name it here.
11197
- *
11198
- * `metadata` is the one slim provably discards: `device-queries.ts#listAll`
11199
- * sets `metadata: null` on every slim row. It is also the largest JSON column
11200
- * on the row, which is why this is worth doing at all.
11201
- *
11202
- * ## What is NOT here, and will not be
11203
- *
11204
- * There is no `where: { type: 'camera' }` companion to this. `isCameraDevice`
11205
- * is a method-presence check (`getStreamSources`), not the persisted `type`, so
11206
- * a doorbell with a camera answers YES while its row says `doorbell`. Filtering
11207
- * the rows by type would strip exactly those devices of their row — and
11208
- * `toDeviceInfo` reads `name` / `location` / `disabled` from the ROW precisely
11209
- * because the live device's copies are stale by construction. The fleet would
11210
- * keep working and start reporting pre-rename names on doorbells. The
11211
- * `isCamera` filter stays in JS.
11212
- */
11213
- var DEVICE_ROWS_SLIM_COLUMNS = DEVICE_ROWS_COLUMNS.map((c) => c.name).filter((name) => name !== "id" && name !== "metadata");
11214
- var DEVICE_ROWS_INDEXES = [
11215
- {
11216
- name: "idx_dm_devices_addon_stable",
11217
- columns: ["addonId", "stableId"]
11218
- },
11219
- {
11220
- name: "idx_dm_devices_parent",
11221
- columns: ["parentDeviceId"]
11222
- },
11223
- {
11224
- name: "idx_dm_devices_integration",
11225
- columns: ["integrationId"]
11226
- },
11227
- {
11228
- name: "idx_dm_devices_alias",
11229
- columns: ["alias"]
11230
- }
11231
- ];
11232
- /** Adapt `ctx.api.settingsStore` (tRPC namespace) to {@link DeviceRowBackend}. */
11233
- function deviceRowBackendOf(client) {
11234
- return {
11235
- declareCollection: async (input) => {
11236
- await client.declareCollection.mutate(input);
11237
- },
11238
- get: (input) => client.get.query(input),
11239
- set: async (input) => {
11240
- await client.set.mutate(input);
11241
- },
11242
- query: (input) => client.query.query(input),
11243
- updateWhere: (input) => client.updateWhere.mutate(input),
11244
- delete: async (input) => {
11245
- await client.delete.mutate(input);
11246
- },
11247
- count: (input) => client.count.query(input)
11248
- };
11249
- }
11250
- function isPlainObject$1(value) {
11251
- return value !== null && typeof value === "object" && !Array.isArray(value);
11252
- }
11253
- function readString(value) {
11254
- return typeof value === "string" ? value : void 0;
11255
- }
11256
- function readNumber(value) {
11257
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
11258
- }
11259
- function readBoolean(value) {
11260
- if (typeof value === "boolean") return value;
11261
- if (value === 1) return true;
11262
- if (value === 0) return false;
11263
- }
11264
- function readStringArray(value) {
11265
- if (!Array.isArray(value)) return void 0;
11266
- const out = [];
11267
- for (const entry of value) if (typeof entry === "string") out.push(entry);
11268
- return out;
11269
- }
11270
- /**
11271
- * Decode one stored row.
11272
- *
11273
- * Returns `null` for a row missing an identity field the rest of the system
11274
- * treats as an invariant (`deviceId` / `addonId` / `stableId` / `type` /
11275
- * `name`). A row like that cannot be projected into a `DeviceInfo` and taking
11276
- * the whole fleet read down for it would be worse — the caller logs the skip.
11277
- */
11278
- function decodeDeviceRow(data) {
11279
- const deviceId = readNumber(data["deviceId"]);
11280
- const addonId = readString(data["addonId"]);
11281
- const stableId = readString(data["stableId"]);
11282
- const storedType = readString(data["type"]);
11283
- const type = storedType === void 0 ? void 0 : require_dist.canonicalStoredDeviceType(storedType);
11284
- const name = readString(data["name"]);
11285
- if (deviceId === void 0 || addonId === void 0 || stableId === void 0 || type === void 0 || name === void 0) return null;
11286
- const location = readString(data["location"]);
11287
- const tags = readStringArray(data["tags"]);
11288
- const parentDeviceId = readNumber(data["parentDeviceId"]);
11289
- const userNamed = readBoolean(data["userNamed"]);
11290
- const features = readStringArray(data["features"]);
11291
- const exportFingerprint = readString(data["exportFingerprint"]);
11292
- const integrationId = readString(data["integrationId"]);
11293
- const linkDeviceId = readNumber(data["linkDeviceId"]);
11294
- const primaryChildEntityId = readString(data["primaryChildEntityId"]);
11295
- const role = readString(data["role"]);
11296
- const alias = readString(data["alias"]);
11297
- const rawChildLayout = data["childLayout"];
11298
- const primaryChildPreference = readStringArray(data["primaryChildPreference"]);
11299
- const rawDisplay = data["display"];
11300
- const rawMetadata = data["metadata"];
11301
- const identifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["identifiers"]);
11302
- const attachedIdentifiers = require_dist.DeviceIdentifiersSchema.safeParse(data["attachedIdentifiers"]);
11303
- const attachedRetained = require_dist.DeviceIdentifierKeySchema.array().min(1).safeParse(data["attachedRetained"]);
11304
- return {
11305
- meta: {
11306
- id: deviceId,
11307
- addonId,
11308
- stableId,
11309
- type,
11310
- name,
11311
- location: location ?? null,
11312
- ...tags !== void 0 && tags.length > 0 ? { tags: [...tags] } : {},
11313
- disabled: readBoolean(data["disabled"]) ?? false,
11314
- parentDeviceId: parentDeviceId ?? null,
11315
- ...alias !== void 0 ? { alias } : {},
11316
- ...userNamed !== void 0 ? { userNamed } : {},
11317
- ...features !== void 0 ? { features } : {},
11318
- ...exportFingerprint !== void 0 ? { exportFingerprint } : {},
11319
- ...integrationId !== void 0 ? { integrationId } : {},
11320
- ...linkDeviceId !== void 0 ? { linkDeviceId } : {},
11321
- ...primaryChildEntityId !== void 0 ? { primaryChildEntityId } : {},
11322
- ...isChildLayout(rawChildLayout) ? { childLayout: rawChildLayout } : {},
11323
- ...primaryChildPreference !== void 0 ? { primaryChildPreference } : {},
11324
- ...role !== void 0 ? { role } : {},
11325
- ...isPlainObject$1(rawDisplay) ? { display: toDisplayOverride(rawDisplay) } : {},
11326
- ...identifiers.success ? { identifiers: identifiers.data } : {},
11327
- ...attachedIdentifiers.success ? { attachedIdentifiers: attachedIdentifiers.data } : {},
11328
- ...attachedRetained.success ? { attachedRetained: attachedRetained.data } : {}
11329
- },
11330
- metadata: isPlainObject$1(rawMetadata) ? rawMetadata : null,
11331
- registered: readBoolean(data["registered"]) ?? false
11332
- };
11333
- }
11334
- /**
11335
- * `ChildLayout` is a JSON column: what comes back is whatever was written.
11336
- * The projection hands it to the UI untouched, so the only thing worth
11337
- * checking is that it is still the array shape the writer put in.
11338
- */
11339
- function isChildLayout(value) {
11340
- return Array.isArray(value);
11341
- }
11342
- /**
11343
- * `DeviceDisplayOverride` is likewise stored verbatim in a JSON column. It is
11344
- * an all-optional record, so any object round-trips; the write path
11345
- * (`normalizeDisplayOverride`) is what gives it shape.
11346
- */
11347
- function toDisplayOverride(value) {
11348
- return value;
11349
- }
11350
- /** Full-row value for an upsert: identity + every field of the meta record. */
11351
- function encodeDeviceRow(meta, extra = {}) {
11352
- const row = {
11353
- id: String(meta.id),
11354
- deviceId: meta.id,
11355
- addonId: meta.addonId,
11356
- stableId: meta.stableId,
11357
- type: meta.type,
11358
- name: meta.name,
11359
- alias: meta.alias ?? null,
11360
- userNamed: meta.userNamed ?? null,
11361
- location: meta.location,
11362
- tags: meta.tags === void 0 || meta.tags.length === 0 ? null : [...meta.tags],
11363
- disabled: meta.disabled,
11364
- parentDeviceId: meta.parentDeviceId,
11365
- registered: extra.registered ?? false,
11366
- features: meta.features === void 0 ? null : [...meta.features],
11367
- exportFingerprint: meta.exportFingerprint ?? null,
11368
- integrationId: meta.integrationId ?? null,
11369
- linkDeviceId: meta.linkDeviceId ?? null,
11370
- primaryChildEntityId: meta.primaryChildEntityId ?? null,
11371
- childLayout: meta.childLayout ?? null,
11372
- primaryChildPreference: meta.primaryChildPreference === void 0 ? null : [...meta.primaryChildPreference],
11373
- role: meta.role ?? null,
11374
- display: meta.display ?? null,
11375
- identifiers: meta.identifiers ?? null,
11376
- attachedIdentifiers: meta.attachedIdentifiers ?? null,
11377
- attachedRetained: meta.attachedRetained === void 0 ? null : [...meta.attachedRetained]
11378
- };
11379
- if (extra.metadata !== void 0) row["metadata"] = extra.metadata;
11380
- return row;
11381
- }
11382
- /** Column map for a partial write — only the keys the caller actually named. */
11383
- function encodeDeviceRowPatch(patch) {
11384
- const row = {};
11385
- for (const [key, value] of Object.entries(patch)) {
11386
- if (value === void 0) continue;
11387
- row[key] = value;
11388
- }
11389
- return row;
11390
- }
11391
- /**
11392
- * Row access for the device fleet. Every method is a single statement against
11393
- * `device-manager:devices` — there is no in-memory copy of the fleet here and
11394
- * no cache: a per-device question is a primary-key lookup, a fleet question is
11395
- * one indexed scan.
11396
- */
11397
- var DeviceRowStore = class {
11398
- backend;
11399
- logger;
11400
- observer;
11401
- declared = null;
11402
- /** Call-site attribution for fleet reads. Armed only by
11403
- * `CAMSTACK_FLEET_READ_CENSUS_MS`; see `fleet-read-census.ts`. */
11404
- census;
11405
- /**
11406
- * Is the fleet-read census armed right now? Exposed so a caller ABOVE this
11407
- * store (`device-queries.ts`) can skip extracting a caller identity off its
11408
- * input entirely when nobody is measuring — "the boolean field read first"
11409
- * pattern this repo already uses elsewhere to keep a diagnostic seam at
11410
- * zero cost while disarmed.
11411
- */
11412
- get censusArmed() {
11413
- return this.census.armed;
11414
- }
11415
- constructor(backend, logger, census, observer) {
11416
- this.backend = backend;
11417
- this.logger = logger;
11418
- this.observer = observer;
11419
- this.census = census ?? new FleetReadCensus(process.env["CAMSTACK_FLEET_READ_CENSUS_MS"], Date.now());
11420
- if (this.census.armed) {
11421
- const startedAt = Date.now();
11422
- setTimeout(() => this.census.report(this.logger, Date.now() - startedAt), this.census.windowMs).unref?.();
11423
- }
11424
- }
11425
- /**
11426
- * Lazy, idempotent `declareCollection`, memoised on the PROMISE so N
11427
- * concurrent first-callers issue one declaration rather than N. A rejection
11428
- * is not latched — the slot is cleared so the next caller retries instead of
11429
- * inheriting a dead collection forever.
11430
- */
11431
- async declare() {
11432
- const existing = this.declared;
11433
- if (existing !== null) return existing;
11434
- const run = (async () => {
11435
- try {
11436
- await this.backend.declareCollection({
11437
- collection: DEVICE_ROWS_COLLECTION,
11438
- columns: DEVICE_ROWS_COLUMNS,
11439
- indexes: DEVICE_ROWS_INDEXES
11440
- });
11441
- } catch (err) {
11442
- this.declared = null;
11443
- throw err;
11444
- }
11445
- })();
11446
- this.declared = run;
11447
- return run;
11448
- }
11449
- /** One device, by numeric id. `null` when the fleet does not know it. */
11450
- async get(deviceId) {
11451
- await this.declare();
11452
- const raw = await this.backend.get({
11453
- collection: DEVICE_ROWS_COLLECTION,
11454
- key: String(deviceId)
11455
- });
11456
- if (!isPlainObject$1(raw)) return null;
11457
- const decoded = decodeDeviceRow(raw);
11458
- if (decoded === null) {
11459
- this.logger.warn("device row skipped — identity fields missing", { tags: { deviceId } });
11460
- return null;
11461
- }
11462
- return decoded;
11463
- }
11464
- /**
11465
- * Every device, ordered by numeric id.
11466
- *
11467
- * `callerAddonId`, when known, is the addon that ORIGINATED this call —
11468
- * captured off the cap-channel envelope (`CapCallInput.callerAddonId`, set
11469
- * by `LocalChildRegistry` from the registered `childId`), never guessed.
11470
- * Passed straight to the census; a stack walk can never name it (see
11471
- * `fleet-read-census.ts#siteOf`).
11472
- */
11473
- async listAll(callerAddonId) {
11474
- return this.list({
11475
- orderBy: {
11476
- field: "deviceId",
11477
- direction: "asc"
11478
- },
11479
- limit: DEVICE_ROWS_FLEET_LIMIT
11480
- }, void 0, callerAddonId);
11481
- }
11482
- /**
11483
- * The fleet, read as narrowly as the question allows.
11484
- *
11485
- * `listAll` is a full-table `SELECT … ORDER BY "deviceId"` — ~1 017 rows a
11486
- * call on the live hub, 14–54 calls a minute — and its callers then filtered
11487
- * the result in JS. The two filters that CAN be pushed down are here:
11488
- *
11489
- * - `deviceIds` becomes a `whereIn`. The viewer's linked-devices panel asks
11490
- * about ~8 named ids; it was answered by reading the whole ledger. An
11491
- * EMPTY set reads nothing at all rather than degrading to "everything" —
11492
- * a request for no devices is a request, not an omission.
11493
- * - `slim` becomes a column projection, {@link DEVICE_ROWS_SLIM_COLUMNS}.
11494
- *
11495
- * `isCamera` is deliberately NOT one of them — see that constant's note and
11496
- * `device-row-store-filtered.spec.ts`.
11497
- *
11498
- * `callerAddonId` — see {@link listAll}'s doc; same meaning here.
11499
- */
11500
- async listFleet(opts, callerAddonId) {
11501
- if (opts.deviceIds !== void 0 && opts.deviceIds.length === 0) return [];
11502
- return this.list({
11503
- ...opts.deviceIds !== void 0 ? { whereIn: { deviceId: [...new Set(opts.deviceIds)] } } : {},
11504
- orderBy: {
11505
- field: "deviceId",
11506
- direction: "asc"
11507
- },
11508
- limit: DEVICE_ROWS_FLEET_LIMIT
11509
- }, opts.slim === true ? DEVICE_ROWS_SLIM_COLUMNS : void 0, callerAddonId);
11510
- }
11511
- /**
11512
- * Many devices, by numeric id, in ONE query.
11513
- *
11514
- * `get(id)` called once per id in a loop is the primary-key lookup this
11515
- * store exists to make cheap, repeated until it isn't — measured on the
11516
- * live hub 2026-08-25: `get device-manager:devices` at 1 656 calls/min
11517
- * steady-state and 17 687 during boot, exactly one row per call. This
11518
- * collapses that into the same `whereIn` {@link listFleet} already does for
11519
- * a fleet read, keyed by id.
11520
- *
11521
- * A requested id the fleet does not know is simply ABSENT from the map —
11522
- * never a fabricated row, matching {@link get}'s `null`. An empty `ids`
11523
- * reads nothing at all, same as `listFleet({ deviceIds: [] })`.
11524
- */
11525
- async getMany(ids) {
11526
- const rows = await this.listFleet({ deviceIds: ids });
11527
- return new Map(rows.map((row) => [row.meta.id, row]));
11528
- }
11529
- /**
11530
- * The device an addon knows as `stableId`, or `null`.
11531
- *
11532
- * `(addonId, stableId)` is the addon-facing identity — unique by
11533
- * construction, since `allocateDeviceId` is the only thing that mints a row
11534
- * and it returns the existing id for a pair it already knows. A second row
11535
- * for the pair would be a corruption, so this takes the LOWEST id and says
11536
- * so rather than picking arbitrarily.
11537
- */
11538
- async findByStableId(addonId, stableId) {
11539
- const rows = await this.list({
11540
- where: {
11541
- addonId,
11542
- stableId
11543
- },
11544
- orderBy: {
11545
- field: "deviceId",
11546
- direction: "asc"
11547
- },
11548
- limit: 2
11549
- });
11550
- const first = rows[0];
11551
- if (first === void 0) return null;
11552
- if (rows.length > 1) this.logger.warn("duplicate device rows for one (addonId, stableId) — using the lowest id", {
11553
- tags: { deviceId: first.meta.id },
11554
- meta: {
11555
- addonId,
11556
- stableId,
11557
- ids: rows.map((r) => r.meta.id)
11558
- }
11559
- });
11560
- return first;
11561
- }
11562
- /**
11563
- * The device that owns a template alias, or `null`. Aliases are unique, so a
11564
- * second row for one alias would be a corruption: the LOWEST id is answered and
11565
- * the duplicate is said on the record.
11566
- */
11567
- async findByAlias(alias) {
11568
- const rows = await this.list({
11569
- where: { alias },
11570
- orderBy: {
11571
- field: "deviceId",
11572
- direction: "asc"
11573
- },
11574
- limit: 2
11575
- });
11576
- const first = rows[0];
11577
- if (first === void 0) return null;
11578
- if (rows.length > 1) this.logger.warn("duplicate device rows for one alias — using the lowest id", {
11579
- tags: { deviceId: first.meta.id },
11580
- meta: {
11581
- alias,
11582
- ids: rows.map((r) => r.meta.id)
11583
- }
11584
- });
11585
- return first;
11586
- }
11587
- /** Every device owned by one addon, ordered by numeric id. */
11588
- async listByAddon(addonId) {
11589
- return this.list({
11590
- where: { addonId },
11591
- orderBy: {
11592
- field: "deviceId",
11593
- direction: "asc"
11594
- },
11595
- limit: DEVICE_ROWS_FLEET_LIMIT
11596
- });
11597
- }
11598
- /** Every device an integration owns, ordered by numeric id. */
11599
- async listByIntegration(integrationId) {
11600
- return this.list({
11601
- where: { integrationId },
11602
- orderBy: {
11603
- field: "deviceId",
11604
- direction: "asc"
11605
- },
11606
- limit: DEVICE_ROWS_FLEET_LIMIT
11607
- });
11608
- }
11609
- /** Direct children of one device, ordered by numeric id. */
11610
- async listByParent(parentDeviceId) {
11611
- return this.list({
11612
- where: { parentDeviceId },
11613
- orderBy: {
11614
- field: "deviceId",
11615
- direction: "asc"
11616
- },
11617
- limit: DEVICE_ROWS_FLEET_LIMIT
11618
- });
11619
- }
11620
- /**
11621
- * Direct children of MANY devices, in ONE query.
11622
- *
11623
- * `listByParent` called once per parent is the same shape `get` was before
11624
- * {@link getMany}: an indexed lookup this store makes cheap, repeated until
11625
- * it isn't. Measured on the live hub 2026-08-27, 120-second boot window:
11626
- * `DeviceRowStore.list < DeviceRowStore.listByParent < getChildren` at
11627
- * **1 024 calls** — one per device — for 919 rows in total. The BFS in
11628
- * `device-meta-actions.ts#collectDescendants` walked a container tree the
11629
- * same way, one query per node.
11630
- *
11631
- * `whereIn` on the indexed `parentDeviceId` column collapses a level of that
11632
- * walk into a single statement. Contract, verbatim from {@link getMany}: an
11633
- * EMPTY `parentDeviceIds` reads nothing at all rather than degrading to
11634
- * "everything", and a parent with no children — or one the fleet does not
11635
- * know — is simply ABSENT from the map, never an invented empty row.
11636
- */
11637
- async listByParentMany(parentDeviceIds) {
11638
- const out = /* @__PURE__ */ new Map();
11639
- const unique = [...new Set(parentDeviceIds)];
11640
- if (unique.length === 0) return out;
11641
- const rows = await this.list({
11642
- whereIn: { parentDeviceId: unique },
11643
- orderBy: {
11644
- field: "deviceId",
11645
- direction: "asc"
11646
- },
11647
- limit: DEVICE_ROWS_FLEET_LIMIT
11648
- });
11649
- const byParent = /* @__PURE__ */ new Map();
11650
- for (const row of rows) {
11651
- const parent = row.meta.parentDeviceId;
11652
- if (parent === null || parent === void 0) continue;
11653
- const bucket = byParent.get(parent);
11654
- if (bucket === void 0) byParent.set(parent, [row]);
11655
- else bucket.push(row);
11656
- }
11657
- for (const [parent, bucket] of byParent) out.set(parent, bucket);
11658
- return out;
11659
- }
11660
- /** How many devices the fleet holds. Used to tell "empty store" from "gone device". */
11661
- async count() {
11662
- await this.declare();
11663
- return this.backend.count({ collection: DEVICE_ROWS_COLLECTION });
11664
- }
11665
- async list(filter, columns, callerAddonId) {
11666
- const site = this.census.siteOf(callerAddonId);
11667
- await this.declare();
11668
- const records = await this.backend.query({
11669
- collection: DEVICE_ROWS_COLLECTION,
11670
- filter,
11671
- ...columns === void 0 ? {} : { columns }
11672
- });
11673
- this.census.record(site, records.length);
11674
- const out = [];
11675
- for (const record of records) {
11676
- const decoded = decodeDeviceRow(record.data);
11677
- if (decoded === null) {
11678
- this.logger.warn("device row skipped — identity fields missing", { meta: { rowId: record.id } });
11679
- continue;
11680
- }
11681
- out.push(decoded);
11682
- }
11683
- return out;
11684
- }
11685
- /** Insert or replace the whole identity row. */
11686
- async upsert(meta, extra = {}) {
11687
- await this.declare();
11688
- await this.backend.set({
11689
- collection: DEVICE_ROWS_COLLECTION,
11690
- key: String(meta.id),
11691
- value: encodeDeviceRow(meta, extra)
11692
- });
11693
- this.observer?.rowWritten(meta);
11694
- }
11695
- /**
11696
- * Write the named columns of an EXISTING row and nothing else.
11697
- *
11698
- * An UPDATE, deliberately not an upsert: a partial upsert would try to INSERT
11699
- * a row carrying only the patched columns, and SQLite rejects that on the
11700
- * `NOT NULL` identity columns before the primary-key conflict can turn it
11701
- * into an update. Every caller resolves the row under the write lock and
11702
- * throws when it is gone, so matching zero rows means a device was removed
11703
- * between the resolve and the write — the patch is lost, and a lost write
11704
- * that says nothing reads as a write that happened.
11705
- */
11706
- async patch(deviceId, patch) {
11707
- const columns = encodeDeviceRowPatch(patch);
11708
- if (Object.keys(columns).length === 0) return;
11709
- await this.declare();
11710
- const { updated } = await this.backend.updateWhere({
11711
- collection: DEVICE_ROWS_COLLECTION,
11712
- filter: { where: { id: String(deviceId) } },
11713
- data: columns
11714
- });
11715
- if (updated === 0) {
11716
- this.logger.warn("device row patch matched no row — the device was removed under it", {
11717
- tags: { deviceId },
11718
- meta: { columns: Object.keys(columns) }
11719
- });
11720
- return;
11721
- }
11722
- this.observer?.rowPatched(deviceId, patch);
11723
- }
11724
- /**
11725
- * Insert-or-update the registration columns. See {@link DeviceRegistrationRow}
11726
- * for why this is a separate, fully-specified statement rather than a patch.
11727
- */
11728
- async upsertRegistration(row) {
11729
- await this.declare();
11730
- await this.backend.set({
11731
- collection: DEVICE_ROWS_COLLECTION,
11732
- key: String(row.deviceId),
11733
- value: {
11734
- deviceId: row.deviceId,
11735
- addonId: row.addonId,
11736
- stableId: row.stableId,
11737
- type: row.type,
11738
- name: row.name,
11739
- userNamed: row.userNamed,
11740
- location: row.location,
11741
- disabled: row.disabled,
11742
- parentDeviceId: row.parentDeviceId,
11743
- registered: row.registered,
11744
- features: [...row.features],
11745
- exportFingerprint: row.exportFingerprint
11746
- }
11747
- });
11748
- this.observer?.registrationWritten(row);
11749
- }
11750
- /** Drop the device's row. Idempotent. */
11751
- /**
11752
- * Exchange the ids of two devices, carrying their children with them.
11753
- *
11754
- * ## Why this exists as a primitive
11755
- *
11756
- * Replacing a camera means the new hardware has to become the device the rest
11757
- * of the system already knows. Everything general about a camera is keyed on
11758
- * the NUMERIC id and on nothing else — the recording path on disk is
11759
- * `<deviceId>/profile/…`, the hour ledger, the media store and zone ownership
11760
- * carry `deviceId` and not one `stableId` between them, and all four
11761
- * ecosystem exports (Home Assistant, Alexa, HomeKit, Google) key on it too.
11762
- * Moving that work is the expensive, lossy operation. Moving the NUMBER is
11763
- * two rows.
11764
- *
11765
- * ## Children are re-pointed, not renumbered
11766
- *
11767
- * A child keeps its own id and follows its parent: every row whose
11768
- * `parentDeviceId` was `a` now names `b`, and the reverse. Renumbering the
11769
- * children as well would move THEIR general work for no reason — the
11770
- * accessory's own recordings and rules are keyed on the child id, which is
11771
- * not the id being inherited.
11772
- *
11773
- * ## There are no transactions here, so the ORDER is the safety
11774
- *
11775
- * The backing store is a collection API (`set` / `delete` / `updateWhere`);
11776
- * there is no rollback to lean on. So the sequence is chosen to make every
11777
- * crash point LOUD rather than plausible: `a` first moves to a freshly
11778
- * allocated id, which the monotonic counter guarantees was never used and
11779
- * will never be reused. A crash before the end therefore leaves a device
11780
- * missing from its number and a stray at an unfamiliar one — visible in the
11781
- * device list at a glance. What it can never leave is two rows on one number,
11782
- * or a row that looks correct while its children point elsewhere.
11783
- *
11784
- * The caller holds {@link DeviceMetaStore.withMetaWriteLock}. This method does
11785
- * not take it: taking it here would deadlock the migration that has to disable
11786
- * functions on both devices in the same critical section.
11787
- */
11788
- async swapIds(a, b, tempId) {
11789
- const { rowA, rowB, childrenOfA, childrenOfB } = await this.planSwap(a, b, tempId).catch((err) => {
11790
- if (err instanceof MigrationRefusedError) throw err;
11791
- throw new MigrationRefusedError(`[device-manager] swapIds: precheck failed before any row moved — ${err instanceof Error ? err.message : String(err)}`, { cause: err });
11792
- });
11793
- await this.moveRow(rowA, tempId);
11794
- await this.moveRow(rowB, a);
11795
- await this.moveRow({
11796
- ...rowA,
11797
- meta: {
11798
- ...rowA.meta,
11799
- id: tempId
11800
- }
11801
- }, b);
11802
- for (const childId of childrenOfA) await this.patch(childId, { parentDeviceId: b });
11803
- for (const childId of childrenOfB) await this.patch(childId, { parentDeviceId: a });
11804
- this.logger.info("device ids swapped", {
11805
- tags: { deviceId: a },
11806
- meta: {
11807
- a,
11808
- b,
11809
- childrenOfA,
11810
- childrenOfB
11811
- }
11812
- });
11813
- }
11814
- /** The read-only half of {@link swapIds}: every refusal, every read, no write. */
11815
- async planSwap(a, b, tempId) {
11816
- if (a === b) throw new MigrationRefusedError(`[device-manager] swapIds: ${a} and ${b} are the same device`);
11817
- await this.declare();
11818
- const rowA = await this.get(a);
11819
- const rowB = await this.get(b);
11820
- if (rowA === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${a} does not exist`);
11821
- if (rowB === null) throw new MigrationRefusedError(`[device-manager] swapIds: device ${b} does not exist`);
11822
- if (await this.get(tempId) !== null) throw new MigrationRefusedError(`[device-manager] swapIds: temp id ${tempId} is taken`);
11823
- return {
11824
- rowA,
11825
- rowB,
11826
- childrenOfA: (await this.listByParent(a)).map((r) => r.meta.id),
11827
- childrenOfB: (await this.listByParent(b)).map((r) => r.meta.id)
11828
- };
11829
- }
11830
- /** Rewrite a row under a new id and drop the old key. Not exported: the only
11831
- * legitimate reason to move a row is {@link swapIds}. */
11832
- async moveRow(row, toId) {
11833
- await this.upsert({
11834
- ...row.meta,
11835
- id: toId
11836
- }, {
11837
- registered: row.registered,
11838
- metadata: row.metadata
11839
- });
11840
- await this.remove(row.meta.id);
11841
- }
11842
- async remove(deviceId) {
11843
- await this.declare();
11844
- await this.backend.delete({
11845
- collection: DEVICE_ROWS_COLLECTION,
11846
- key: String(deviceId)
11847
- });
11848
- this.observer?.rowRemoved(deviceId);
11849
- }
11850
- /**
11851
- * The retirement door for the three blobs this collection replaced.
11852
- *
11853
- * The purge is gated on THIS collection being non-empty, and the count has to
11854
- * be taken after `declare()` — which is why the owning addon runs it and the
11855
- * settings engine cannot: at the engine's own boot no addon has declared
11856
- * anything, so every successor would read as unreadable, forever.
11857
- */
11858
- retiredRowStore() {
11859
- return {
11860
- hasRow: async (spec) => {
11861
- const raw = await this.backend.get({
11862
- collection: spec.collection,
11863
- key: spec.row
11864
- });
11865
- return raw !== void 0 && raw !== null;
11866
- },
11867
- deleteRow: async (spec) => {
11868
- await this.backend.delete({
11869
- collection: spec.collection,
11870
- key: spec.row
11871
- });
11872
- },
11873
- countRows: async (collection) => {
11874
- await this.declare();
11875
- return this.backend.count({ collection });
11876
- }
11877
- };
11878
- }
11879
- };
11880
- //#endregion
11881
10768
  //#region src/builtins/device-manager/device-state-claims.ts
11882
10769
  function createDeviceStateClaimMethods(deps) {
11883
10770
  const { mirror, index, settings, logger } = deps;
@@ -12272,7 +11159,7 @@ function errorMessage$3(err) {
12272
11159
  * moved yet, so it is a {@link MigrationRefusedError}: the migration refuses
12273
11160
  * and restores both cameras' switches.
12274
11161
  */
12275
- var RuntimeStateDrainError = class extends MigrationRefusedError {
11162
+ var RuntimeStateDrainError = class extends require_device_row_store.MigrationRefusedError {
12276
11163
  deviceId;
12277
11164
  constructor(deviceId, reason, options) {
12278
11165
  super(`migration refused: the runtime state of device ${deviceId} could not be drained before the swap (${reason}) — nothing moved; retry the migration`, options);
@@ -15863,12 +14750,12 @@ var DeviceManagerAddon = class extends require_dist.BaseAddon {
15863
14750
  const settingsStoreApi = this.ctx.api?.settingsStore;
15864
14751
  if (!settingsStoreApi) throw new Error("[device-manager] settings-store API not available — refusing to serve a fleet it cannot persist");
15865
14752
  const identityIndex = new DeviceIdentityIndex();
15866
- const deviceRows = new DeviceRowStore(deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
14753
+ const deviceRows = new require_device_row_store.DeviceRowStore(require_device_row_store.deviceRowBackendOf(settingsStoreApi), this.ctx.logger.child("rows"), void 0, identityIndex);
15867
14754
  await deviceRows.declare();
15868
14755
  this.deviceRows = deviceRows;
15869
14756
  const records = this.ctx.records;
15870
14757
  if (records === void 0) throw new Error("[device-manager] ctx.records is required on the hub");
15871
- await records.declare(deviceManagerRecordKinds);
14758
+ await records.declare(require_device_row_store.deviceManagerRecordKinds);
15872
14759
  const tombstones = DeviceTombstoneStore.of(records, this.ctx.logger.child("tombstones"));
15873
14760
  const identityLinksStore = IdentityLinksStore.of(records);
15874
14761
  await identityLinksStore.load();