@camstack/addon-provider-reolink 1.2.230 → 1.2.231

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.
package/dist/addon.js CHANGED
@@ -106677,7 +106677,7 @@ var ZodIssueCode = {
106677
106677
  var ZodFirstPartyTypeKind;
106678
106678
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
106679
106679
  //#endregion
106680
- //#region ../types/dist/sleep-BX_MqzUe.mjs
106680
+ //#region ../types/dist/sleep-CmjWurK5.mjs
106681
106681
  /**
106682
106682
  * The audio chunk plane's byte format, and the ONE expansion from a coded
106683
106683
  * window to float samples (D455).
@@ -107361,137 +107361,100 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
107361
107361
  blockOwner
107362
107362
  };
107363
107363
  }
107364
- /**
107365
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
107366
- * `read`/`write` are the addon-store or device-store accessors. The whole
107367
- * validated value round-trips on every read/write — the schema is the
107368
- * single source of truth for what is persisted, so no hand-listed field
107369
- * set can drop a key on save.
107370
- */
107371
- function createDurableState(deps) {
107372
- const get = async () => {
107373
- const raw = (await deps.read())[deps.key];
107374
- if (raw === void 0) return deps.fallback;
107375
- const parsed = deps.schema.safeParse(raw);
107376
- if (!parsed.success) {
107377
- deps.onParseError?.(deps.key, parsed.error);
107378
- return deps.fallback;
107379
- }
107380
- return parsed.data;
107381
- };
107382
- const set = async (next) => {
107383
- const validated = deps.schema.parse(next);
107384
- await deps.write({ [deps.key]: validated });
107385
- };
107386
- const update = async (fn) => {
107387
- await set(fn(await get()));
107388
- };
107364
+ /** The record calls the one-switch migration makes, over the migration API. */
107365
+ function switchRecordsOverMigrationApi(api) {
107366
+ return { kind: (definition) => {
107367
+ const handle = api.records.kind(definition);
107368
+ return {
107369
+ get: (id) => handle.get({ id }),
107370
+ put: (input, opts) => handle.put({
107371
+ ...input,
107372
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
107373
+ }),
107374
+ patch: (id, partial) => handle.patch({
107375
+ id,
107376
+ partial
107377
+ })
107378
+ };
107379
+ } };
107380
+ }
107381
+ function integrationRowsApiOver(api) {
107389
107382
  return {
107390
- get,
107391
- set,
107392
- update
107383
+ list: async () => (await api.integrations.list({})).integrations,
107384
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
107385
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
107393
107386
  };
107394
107387
  }
107388
+ var PREFIX = "records/";
107389
+ /** The base of every records failure. `detail` is the human part of the message. */
107390
+ var RecordsError = class extends Error {
107391
+ code;
107392
+ detail;
107393
+ constructor(code, detail) {
107394
+ super(`${PREFIX}${code}: ${detail}`);
107395
+ this.name = "RecordsError";
107396
+ this.code = code;
107397
+ this.detail = detail;
107398
+ }
107399
+ };
107400
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
107401
+ var RevConflictError = class extends RecordsError {
107402
+ constructor(detail) {
107403
+ super("rev-conflict", detail);
107404
+ this.name = "RevConflictError";
107405
+ }
107406
+ };
107407
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
107408
+ var RecordSecretUnavailableError = class extends RecordsError {
107409
+ constructor(detail) {
107410
+ super("secret-unavailable", detail);
107411
+ this.name = "RecordSecretUnavailableError";
107412
+ }
107413
+ };
107414
+ var InvalidRecordError = class extends RecordsError {
107415
+ constructor(detail) {
107416
+ super("invalid-record", detail);
107417
+ this.name = "InvalidRecordError";
107418
+ }
107419
+ };
107420
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
107421
+ var DeclarationRefusedError = class extends RecordsError {
107422
+ constructor(detail) {
107423
+ super("declaration-refused", detail);
107424
+ this.name = "DeclarationRefusedError";
107425
+ }
107426
+ };
107395
107427
  /**
107396
- * Per-node scoping for the shared addon-settings blob.
107397
- *
107398
- * An addon's settings store is hub-central (the `addon-settings` cap is
107399
- * hub-routed — the hub instance answers for every node), so fields whose
107400
- * value is a NODE fact (decoder backend, engine pick, probed hardware
107401
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
107402
- * the single shared blob. The SCHEMA field key stays bare: the write path
107403
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
107404
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
107405
- * back, so UI forms and `resolveConfig` only ever see the bare key.
107406
- *
107407
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
107408
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
107409
- * schema and routes reads/writes through these helpers.
107410
- *
107411
- * ## No bare-key fallback — deliberate
107412
- *
107413
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
107414
- * scoped key resolves to `undefined` so the field's schema `default` wins —
107415
- * NEVER `store[base]` and never another node's value. A bare legacy key in
107416
- * the store is invisible to every node, hub included, so one node's
107417
- * selection can never leak onto another. (This generalizes the
107418
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
107419
- * arbitrary set of per-node field keys.)
107420
- *
107421
- * Pure functions only — no I/O, no imports beyond the language. This is a
107422
- * LEAF module: import it via its deep path, never from the root barrel.
107423
- */
107424
- /**
107425
- * Normalize a raw kernel node id to the bare node id used for scoping.
107426
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
107427
- * processes; per-node settings are per-NODE, so strip the addon segment.
107428
- * `undefined` / `null` / empty falls back to `'hub'`.
107429
- */
107430
- function normalizeNodeId(raw) {
107431
- if (raw === void 0 || raw === null || raw === "") return "hub";
107432
- const slashIdx = raw.indexOf("/");
107433
- if (slashIdx < 0) return raw;
107434
- const bare = raw.slice(0, slashIdx);
107435
- return bare === "" ? "hub" : bare;
107436
- }
107437
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
107438
- function nodeScopedKey(base, nodeId) {
107439
- return `${base}@${normalizeNodeId(nodeId)}`;
107440
- }
107441
- /**
107442
- * Read a node's value for a per-node field from the raw shared store:
107443
- * the node-scoped key when present, otherwise `undefined`.
107444
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
107445
- * schema `default` win on `undefined`.
107428
+ * A link that may stay empty (absent): for a link the addon fills itself, or one an instance does not
107429
+ * always need. The meta rides on the optional wrapper, where {@link linksOfKind} reads it.
107446
107430
  */
107447
- function readNodeValue(store, base, nodeId) {
107448
- return store[nodeScopedKey(base, nodeId)];
107431
+ function optionalLinkField(target) {
107432
+ return string().optional().meta({ link: target });
107449
107433
  }
107450
- /**
107451
- * Re-map a UI/settings patch so every bare perNode field persists under the
107452
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
107453
- * the write path so a save for one node never clobbers another node's value
107454
- * (and the bare key is never written). Returns a new object — the input
107455
- * patch is not mutated.
107456
- */
107457
- function scopePatch(patch, perNodeKeys, nodeId) {
107458
- const out = {};
107459
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
107460
- return out;
107434
+ function linkTargetOf(meta) {
107435
+ if (typeof meta !== "object" || meta === null) return void 0;
107436
+ const link = Reflect.get(meta, "link");
107437
+ const parsed = LinkTargetSchema.safeParse(link);
107438
+ return parsed.success ? parsed.data : void 0;
107461
107439
  }
107462
- /**
107463
- * Project the raw shared store onto the bare schema keys for ONE node so a
107464
- * UI schema (whose field keys are bare) hydrates from that node's own
107465
- * values:
107466
- *
107467
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
107468
- * - Every bare perNode key is dropped from the pass-through (a stray bare
107469
- * legacy key must never hydrate any node — no bare fallback).
107470
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
107471
- * each bare perNode key; when the node has no scoped key the bare key is
107472
- * left ABSENT so the field's schema `default` wins.
107473
- *
107474
- * Returns a new object — the input store is not mutated.
107475
- */
107476
- function projectStore(store, perNodeKeys, nodeId) {
107477
- const out = {};
107478
- for (const [key, value] of Object.entries(store)) {
107479
- if (key.includes("@")) continue;
107480
- if (perNodeKeys.has(key)) continue;
107481
- out[key] = value;
107482
- }
107483
- for (const base of perNodeKeys) {
107484
- const value = readNodeValue(store, base, nodeId);
107485
- if (value !== void 0) out[base] = value;
107440
+ var LinkTargetSchema = object({
107441
+ cap: string().min(1),
107442
+ kind: string().min(1).optional()
107443
+ });
107444
+ /** The links a kind declares, read from the meta of its body fields. */
107445
+ function linksOfKind(kind) {
107446
+ const schema = kind.schema;
107447
+ if (!(schema instanceof ZodObject)) return [];
107448
+ const links = [];
107449
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
107450
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
107451
+ if (to !== void 0) links.push({
107452
+ field,
107453
+ to
107454
+ });
107486
107455
  }
107487
- return out;
107456
+ return links;
107488
107457
  }
107489
- /** Every scope, in the order the guard and the docs list them. */
107490
- var SCOPED_SETTINGS_SCOPES = [
107491
- "cluster",
107492
- "device-defaults",
107493
- "node"
107494
- ];
107495
107458
  /**
107496
107459
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
107497
107460
  *
@@ -107626,6 +107589,652 @@ function parseSecretRef(ref) {
107626
107589
  fieldPath
107627
107590
  };
107628
107591
  }
107592
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
107593
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
107594
+ var RECORD_DATABASES = ["settings", "events"];
107595
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
107596
+ var RECORD_CLASSES = [
107597
+ "config",
107598
+ "ledger",
107599
+ "audit",
107600
+ "mirror",
107601
+ "ephemeral"
107602
+ ];
107603
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
107604
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
107605
+ var RECORD_BATCH_MAX = 1e3;
107606
+ var RECORD_QUERY_MAX = 1e3;
107607
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
107608
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
107609
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
107610
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
107611
+ /**
107612
+ * Secret fields of a record, addressed the way a Zod schema declares them
107613
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
107614
+ * (`auth.accessToken`, `headers[].value`).
107615
+ *
107616
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
107617
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
107618
+ * key releases exactly that key's secret.
107619
+ *
107620
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
107621
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
107622
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
107623
+ * leaf names its element: `headers[X-Api].value`.
107624
+ *
107625
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
107626
+ */
107627
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
107628
+ function parseSecretPath(path) {
107629
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
107630
+ return path.split(".").map((raw) => {
107631
+ const each = raw.endsWith("[]");
107632
+ const map = raw.endsWith("{}");
107633
+ const key = each || map ? raw.slice(0, -2) : raw;
107634
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
107635
+ return {
107636
+ key,
107637
+ each,
107638
+ map
107639
+ };
107640
+ });
107641
+ }
107642
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
107643
+ function secretArrayPrefixes(path) {
107644
+ const segments = parseSecretPath(path);
107645
+ const prefixes = [];
107646
+ const walked = [];
107647
+ for (const segment of segments) {
107648
+ walked.push(segment.key);
107649
+ if (segment.each) prefixes.push(walked.join("."));
107650
+ }
107651
+ return prefixes;
107652
+ }
107653
+ function isRecord$6(value) {
107654
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107655
+ }
107656
+ function elementId(element, idKey, declared, prefix) {
107657
+ const id = isRecord$6(element) ? element[idKey] : void 0;
107658
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
107659
+ return id;
107660
+ }
107661
+ /**
107662
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
107663
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
107664
+ * result is a new body, `data` is untouched.
107665
+ */
107666
+ var REMOVE_LEAF = Symbol("remove-leaf");
107667
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
107668
+ if (!isRecord$6(node)) return node;
107669
+ const segment = segments[index];
107670
+ if (segment === void 0) return node;
107671
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
107672
+ const child = node[segment.key];
107673
+ const keys = [...walkedKeys, segment.key];
107674
+ const last = index === segments.length - 1;
107675
+ if (segment.each) {
107676
+ if (!Array.isArray(child)) return node;
107677
+ const prefix = keys.join(".");
107678
+ const idKey = arrayKeys[prefix];
107679
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
107680
+ const mapped = child.map((element) => {
107681
+ const id = elementId(element, idKey, declared, prefix);
107682
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
107683
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
107684
+ });
107685
+ return {
107686
+ ...node,
107687
+ [segment.key]: mapped
107688
+ };
107689
+ }
107690
+ if (segment.map) {
107691
+ if (!isRecord$6(child)) return node;
107692
+ const kept = Object.entries(child).map(([mapKey, value]) => {
107693
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
107694
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
107695
+ return [mapKey, visit({
107696
+ declared,
107697
+ concrete,
107698
+ value
107699
+ })];
107700
+ }).filter(([, value]) => value !== REMOVE_LEAF);
107701
+ return {
107702
+ ...node,
107703
+ [segment.key]: Object.fromEntries(kept)
107704
+ };
107705
+ }
107706
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
107707
+ if (last) {
107708
+ const replacement = visit({
107709
+ declared,
107710
+ concrete,
107711
+ value: child
107712
+ });
107713
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
107714
+ return {
107715
+ ...node,
107716
+ [segment.key]: replacement
107717
+ };
107718
+ }
107719
+ return {
107720
+ ...node,
107721
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
107722
+ };
107723
+ }
107724
+ /** Replace/remove every present secret leaf; returns a NEW body. */
107725
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
107726
+ let current = data;
107727
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
107728
+ return current;
107729
+ }
107730
+ /** Every present secret leaf, read-only. */
107731
+ function collectSecretLeaves(data, paths, arrayKeys) {
107732
+ const found = [];
107733
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
107734
+ found.push(leaf);
107735
+ return leaf.value;
107736
+ });
107737
+ return found;
107738
+ }
107739
+ /**
107740
+ * The keychain collection name a kind's secrets live under. Prefixed so a
107741
+ * record's refs never collide with the refs a legacy collection of the same name
107742
+ * already holds during an adoption.
107743
+ */
107744
+ function recordSecretCollection(kind) {
107745
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
107746
+ }
107747
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
107748
+ function recordSecretRef(owner, kind, rowId, concretePath) {
107749
+ return buildSecretRef({
107750
+ owner,
107751
+ scope: {
107752
+ kind: "row",
107753
+ collection: recordSecretCollection(kind),
107754
+ rowId
107755
+ },
107756
+ fieldPath: concretePath
107757
+ });
107758
+ }
107759
+ /**
107760
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
107761
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
107762
+ * token. The form hands it to the secret field, which reveals the value by ref
107763
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
107764
+ * stored secret (the records door reads a view as KEEP).
107765
+ *
107766
+ * ONE implementation for the entries service and for every addon that serves
107767
+ * its own instances (`RecordIntegrationInstances`).
107768
+ */
107769
+ function isRecord$5(value) {
107770
+ return typeof value === "object" && value !== null && !Array.isArray(value);
107771
+ }
107772
+ function secretViewsOf(owner, kind, id, decl, data) {
107773
+ if (decl.secretPaths.length === 0) return data;
107774
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
107775
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
107776
+ return {
107777
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
107778
+ v: 1,
107779
+ set: true
107780
+ };
107781
+ });
107782
+ return isRecord$5(shown) ? shown : data;
107783
+ }
107784
+ /** The most instances one addon lists (an integrations page, not a table). */
107785
+ var INSTANCES_LIST_MAX = 1e3;
107786
+ /**
107787
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
107788
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
107789
+ */
107790
+ function isInstanceEnabled(body) {
107791
+ return body.enabled !== false;
107792
+ }
107793
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
107794
+ var SWITCH_KEY = "enabled";
107795
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
107796
+ function topLevelSecretKeys(paths) {
107797
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
107798
+ }
107799
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
107800
+ function secretMapKeys(paths) {
107801
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
107802
+ }
107803
+ /**
107804
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
107805
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
107806
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
107807
+ */
107808
+ function secretMapPatch(value) {
107809
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
107810
+ const out = {};
107811
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
107812
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
107813
+ return Object.keys(out).length > 0 ? out : null;
107814
+ }
107815
+ var RecordIntegrationInstances = class {
107816
+ records;
107817
+ kind;
107818
+ hooks;
107819
+ handle;
107820
+ secretKeys;
107821
+ secretMaps;
107822
+ nameField;
107823
+ switchListeners = /* @__PURE__ */ new Set();
107824
+ constructor(records, kind, hooks) {
107825
+ this.records = records;
107826
+ this.kind = kind;
107827
+ this.hooks = hooks;
107828
+ this.handle = records.kind(kind);
107829
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
107830
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
107831
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
107832
+ }
107833
+ /**
107834
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
107835
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
107836
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
107837
+ */
107838
+ async readResolved(id) {
107839
+ try {
107840
+ const record = await this.handle.getResolved(id);
107841
+ return record === null ? null : {
107842
+ id,
107843
+ body: record.data,
107844
+ enabled: isInstanceEnabled(record.data),
107845
+ secrets: "resolved"
107846
+ };
107847
+ } catch (err) {
107848
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
107849
+ const stored = await this.handle.get(id);
107850
+ if (stored === null) return null;
107851
+ return {
107852
+ id,
107853
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
107854
+ enabled: isInstanceEnabled(stored.data),
107855
+ secrets: "unavailable"
107856
+ };
107857
+ }
107858
+ }
107859
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
107860
+ async getResolved(id) {
107861
+ return (await this.readResolved(id))?.body ?? null;
107862
+ }
107863
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
107864
+ async listResolved() {
107865
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
107866
+ const out = [];
107867
+ for (const record of page.records) {
107868
+ const read = await this.readResolved(record.id);
107869
+ if (read !== null) out.push(read);
107870
+ }
107871
+ return out;
107872
+ }
107873
+ viewOf(record) {
107874
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
107875
+ const rawName = record.data[this.nameField];
107876
+ const kind = this.hooks.kindOf?.(record.data);
107877
+ const health = this.hooks.health?.(record.data, record.id);
107878
+ return {
107879
+ id: record.id,
107880
+ name: typeof rawName === "string" ? rawName : record.id,
107881
+ configured: this.hooks.configured(record.data),
107882
+ enabled: isInstanceEnabled(record.data),
107883
+ formValues: shown,
107884
+ ...kind !== void 0 ? { kind } : {},
107885
+ ...health?.status !== void 0 ? { status: health.status } : {},
107886
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
107887
+ };
107888
+ }
107889
+ describe = async () => {
107890
+ const declared = linksOfKind(this.kind);
107891
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
107892
+ kind: this.kind.name,
107893
+ field: link.field,
107894
+ to: link.to
107895
+ })) };
107896
+ return {
107897
+ ...this.hooks.description,
107898
+ ...links,
107899
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
107900
+ };
107901
+ };
107902
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
107903
+ listInstances = async () => {
107904
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
107905
+ };
107906
+ getInstance = async ({ id }) => {
107907
+ const record = await this.handle.get(id);
107908
+ return record === null ? null : this.viewOf(record);
107909
+ };
107910
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
107911
+ createInstance = async ({ id, name, kind, values }) => {
107912
+ const minted = id ?? this.hooks.mintId?.({
107913
+ name,
107914
+ ...kind !== void 0 ? { kind } : {}
107915
+ });
107916
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
107917
+ await this.handle.put({
107918
+ id: minted,
107919
+ data: this.hooks.initialBody(name, kind)
107920
+ }, { ifRev: 0 });
107921
+ const patch = this.patchOf(values ?? {});
107922
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
107923
+ await this.hooks.onChanged?.(minted, "created");
107924
+ return { id: minted };
107925
+ };
107926
+ updateInstance = async ({ id, name, values }) => {
107927
+ const patch = this.patchOf(values);
107928
+ if (name !== void 0) patch[this.nameField] = name;
107929
+ await this.handle.patch(id, patch);
107930
+ await this.hooks.onChanged?.(id, "updated");
107931
+ return { ok: true };
107932
+ };
107933
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
107934
+ patchOf(values) {
107935
+ const patch = {};
107936
+ for (const [key, value] of Object.entries(values)) {
107937
+ if (value === void 0) continue;
107938
+ if (key === "enabled") continue;
107939
+ if (this.secretMaps.has(key)) {
107940
+ const entries = secretMapPatch(value);
107941
+ if (entries !== null) patch[key] = entries;
107942
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
107943
+ else if (isSecretClear(value)) patch[key] = null;
107944
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
107945
+ }
107946
+ return patch;
107947
+ }
107948
+ /**
107949
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
107950
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
107951
+ * addon reconciles from the record, whichever way it flipped.
107952
+ */
107953
+ onSwitched(listener) {
107954
+ this.switchListeners.add(listener);
107955
+ }
107956
+ /**
107957
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
107958
+ * configured thing is an instance, so an id with no record yet (a default integration that was
107959
+ * never configured) gets its record from `initialBody` before the switch is written.
107960
+ */
107961
+ setInstanceEnabled = async ({ id, enabled }) => {
107962
+ if (await this.handle.get(id) === null) await this.handle.put({
107963
+ id,
107964
+ data: this.hooks.initialBody(id)
107965
+ }, { ifRev: 0 });
107966
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
107967
+ await this.hooks.onChanged?.(id, "enabled");
107968
+ for (const listener of this.switchListeners) await listener(id, enabled);
107969
+ return { ok: true };
107970
+ };
107971
+ /** The row and its keychain refs go together (the records door). */
107972
+ deleteInstance = async ({ id }) => {
107973
+ await this.handle.delete(id);
107974
+ await this.hooks.onChanged?.(id, "deleted");
107975
+ return { ok: true };
107976
+ };
107977
+ testInstance = async (input) => {
107978
+ if (this.hooks.test === void 0) return {
107979
+ success: false,
107980
+ status: "unsupported",
107981
+ error: "This integration declares no connection test"
107982
+ };
107983
+ return this.hooks.test(input);
107984
+ };
107985
+ /** The flat provider object to hand to `registerProvider`. */
107986
+ toProvider() {
107987
+ return {
107988
+ describe: this.describe,
107989
+ instanceFormSchema: this.instanceFormSchema,
107990
+ listInstances: this.listInstances,
107991
+ getInstance: this.getInstance,
107992
+ createInstance: this.createInstance,
107993
+ updateInstance: this.updateInstance,
107994
+ setInstanceEnabled: this.setInstanceEnabled,
107995
+ deleteInstance: this.deleteInstance,
107996
+ testInstance: this.testInstance
107997
+ };
107998
+ }
107999
+ };
108000
+ /**
108001
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
108002
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
108003
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
108004
+ *
108005
+ * For every registry row of the addon that is OFF:
108006
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
108007
+ * (a default integration that never had settings, Reolink's among them);
108008
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
108009
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
108010
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
108011
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
108012
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
108013
+ *
108014
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
108015
+ * which is also why `integrations.list` still answers the stored column at that point.
108016
+ */
108017
+ function registrySwitchToBodyId(addonId, date) {
108018
+ return `${addonId}/${date}-registry-switch-to-body`;
108019
+ }
108020
+ async function moveRegistrySwitchToBody(ports, spec) {
108021
+ const rows = await ports.listIntegrations(spec.addonId);
108022
+ let created = 0;
108023
+ let switched = 0;
108024
+ let kept = 0;
108025
+ for (const row of rows) {
108026
+ if (row.enabled) continue;
108027
+ const body = await ports.readBody(row.id);
108028
+ if (body === null) {
108029
+ if (await ports.createRecord(row.id, {
108030
+ ...spec.initialBody(row.name),
108031
+ ["enabled"]: false
108032
+ }) === "created") created += 1;
108033
+ else kept += 1;
108034
+ continue;
108035
+ }
108036
+ if ("enabled" in body) {
108037
+ kept += 1;
108038
+ continue;
108039
+ }
108040
+ await ports.switchOff(row.id);
108041
+ switched += 1;
108042
+ }
108043
+ const summary = {
108044
+ integrations: rows.length,
108045
+ off: rows.filter((r) => !r.enabled).length,
108046
+ created,
108047
+ switched,
108048
+ kept
108049
+ };
108050
+ return created === 0 && switched === 0 ? {
108051
+ outcome: "already-done",
108052
+ summary
108053
+ } : {
108054
+ outcome: "done",
108055
+ summary
108056
+ };
108057
+ }
108058
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
108059
+ function registrySwitchToBodyMigration(spec) {
108060
+ return {
108061
+ meta: {
108062
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
108063
+ owner: spec.addonId,
108064
+ level: "addon-state",
108065
+ seq: spec.seq,
108066
+ dependsOn: [],
108067
+ store: "settings",
108068
+ scope: "cluster",
108069
+ onFailure: "block-owner",
108070
+ bodyKind: "procedure",
108071
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
108072
+ fixtureMark: "enabled"
108073
+ },
108074
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
108075
+ addonId: spec.addonId,
108076
+ initialBody: spec.initialBody
108077
+ })
108078
+ };
108079
+ }
108080
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
108081
+ function registrySwitchPortsOver(deps) {
108082
+ const handle = deps.records.kind({
108083
+ name: deps.kind.name,
108084
+ declaration: deps.kind.declaration,
108085
+ schema: record(string(), unknown())
108086
+ });
108087
+ return {
108088
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
108089
+ id: i.id,
108090
+ name: i.name,
108091
+ enabled: i.enabled !== false
108092
+ })),
108093
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
108094
+ createRecord: async (id, body) => {
108095
+ if (await handle.get(id) !== null) return "exists";
108096
+ await handle.put({
108097
+ id,
108098
+ data: body
108099
+ }, { ifRev: 0 });
108100
+ return "created";
108101
+ },
108102
+ switchOff: async (id) => {
108103
+ await handle.patch(id, { [SWITCH_KEY]: false });
108104
+ }
108105
+ };
108106
+ }
108107
+ /**
108108
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
108109
+ * `read`/`write` are the addon-store or device-store accessors. The whole
108110
+ * validated value round-trips on every read/write — the schema is the
108111
+ * single source of truth for what is persisted, so no hand-listed field
108112
+ * set can drop a key on save.
108113
+ */
108114
+ function createDurableState(deps) {
108115
+ const get = async () => {
108116
+ const raw = (await deps.read())[deps.key];
108117
+ if (raw === void 0) return deps.fallback;
108118
+ const parsed = deps.schema.safeParse(raw);
108119
+ if (!parsed.success) {
108120
+ deps.onParseError?.(deps.key, parsed.error);
108121
+ return deps.fallback;
108122
+ }
108123
+ return parsed.data;
108124
+ };
108125
+ const set = async (next) => {
108126
+ const validated = deps.schema.parse(next);
108127
+ await deps.write({ [deps.key]: validated });
108128
+ };
108129
+ const update = async (fn) => {
108130
+ await set(fn(await get()));
108131
+ };
108132
+ return {
108133
+ get,
108134
+ set,
108135
+ update
108136
+ };
108137
+ }
108138
+ /**
108139
+ * Per-node scoping for the shared addon-settings blob.
108140
+ *
108141
+ * An addon's settings store is hub-central (the `addon-settings` cap is
108142
+ * hub-routed — the hub instance answers for every node), so fields whose
108143
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
108144
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
108145
+ * the single shared blob. The SCHEMA field key stays bare: the write path
108146
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
108147
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
108148
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
108149
+ *
108150
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
108151
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
108152
+ * schema and routes reads/writes through these helpers.
108153
+ *
108154
+ * ## No bare-key fallback — deliberate
108155
+ *
108156
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
108157
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
108158
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
108159
+ * the store is invisible to every node, hub included, so one node's
108160
+ * selection can never leak onto another. (This generalizes the
108161
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
108162
+ * arbitrary set of per-node field keys.)
108163
+ *
108164
+ * Pure functions only — no I/O, no imports beyond the language. This is a
108165
+ * LEAF module: import it via its deep path, never from the root barrel.
108166
+ */
108167
+ /**
108168
+ * Normalize a raw kernel node id to the bare node id used for scoping.
108169
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
108170
+ * processes; per-node settings are per-NODE, so strip the addon segment.
108171
+ * `undefined` / `null` / empty falls back to `'hub'`.
108172
+ */
108173
+ function normalizeNodeId(raw) {
108174
+ if (raw === void 0 || raw === null || raw === "") return "hub";
108175
+ const slashIdx = raw.indexOf("/");
108176
+ if (slashIdx < 0) return raw;
108177
+ const bare = raw.slice(0, slashIdx);
108178
+ return bare === "" ? "hub" : bare;
108179
+ }
108180
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
108181
+ function nodeScopedKey(base, nodeId) {
108182
+ return `${base}@${normalizeNodeId(nodeId)}`;
108183
+ }
108184
+ /**
108185
+ * Read a node's value for a per-node field from the raw shared store:
108186
+ * the node-scoped key when present, otherwise `undefined`.
108187
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
108188
+ * schema `default` win on `undefined`.
108189
+ */
108190
+ function readNodeValue(store, base, nodeId) {
108191
+ return store[nodeScopedKey(base, nodeId)];
108192
+ }
108193
+ /**
108194
+ * Re-map a UI/settings patch so every bare perNode field persists under the
108195
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
108196
+ * the write path so a save for one node never clobbers another node's value
108197
+ * (and the bare key is never written). Returns a new object — the input
108198
+ * patch is not mutated.
108199
+ */
108200
+ function scopePatch(patch, perNodeKeys, nodeId) {
108201
+ const out = {};
108202
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
108203
+ return out;
108204
+ }
108205
+ /**
108206
+ * Project the raw shared store onto the bare schema keys for ONE node so a
108207
+ * UI schema (whose field keys are bare) hydrates from that node's own
108208
+ * values:
108209
+ *
108210
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
108211
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
108212
+ * legacy key must never hydrate any node — no bare fallback).
108213
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
108214
+ * each bare perNode key; when the node has no scoped key the bare key is
108215
+ * left ABSENT so the field's schema `default` wins.
108216
+ *
108217
+ * Returns a new object — the input store is not mutated.
108218
+ */
108219
+ function projectStore(store, perNodeKeys, nodeId) {
108220
+ const out = {};
108221
+ for (const [key, value] of Object.entries(store)) {
108222
+ if (key.includes("@")) continue;
108223
+ if (perNodeKeys.has(key)) continue;
108224
+ out[key] = value;
108225
+ }
108226
+ for (const base of perNodeKeys) {
108227
+ const value = readNodeValue(store, base, nodeId);
108228
+ if (value !== void 0) out[base] = value;
108229
+ }
108230
+ return out;
108231
+ }
108232
+ /** Every scope, in the order the guard and the docs list them. */
108233
+ var SCOPED_SETTINGS_SCOPES = [
108234
+ "cluster",
108235
+ "device-defaults",
108236
+ "node"
108237
+ ];
107629
108238
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
107630
108239
  var KeychainWriteRefusedError = class extends Error {
107631
108240
  fieldPath;
@@ -107636,7 +108245,7 @@ var KeychainWriteRefusedError = class extends Error {
107636
108245
  }
107637
108246
  };
107638
108247
  var KEEP = { kind: "keep" };
107639
- function isRecord$6(value) {
108248
+ function isRecord$4(value) {
107640
108249
  return typeof value === "object" && value !== null && !Array.isArray(value);
107641
108250
  }
107642
108251
  function defaultMintId() {
@@ -107649,7 +108258,7 @@ function collectSecretMarkerRefs(value, out = []) {
107649
108258
  return out;
107650
108259
  }
107651
108260
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
107652
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
108261
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
107653
108262
  return out;
107654
108263
  }
107655
108264
  async function storedValueEquals(secrets, marker, candidate) {
@@ -107704,7 +108313,7 @@ function rowId(row, idKey) {
107704
108313
  return null;
107705
108314
  }
107706
108315
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
107707
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
108316
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
107708
108317
  if (!Array.isArray(incoming)) {
107709
108318
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
107710
108319
  return {
@@ -107720,7 +108329,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
107720
108329
  const kept = /* @__PURE__ */ new Set();
107721
108330
  const rows = [];
107722
108331
  for (const row of incoming) {
107723
- if (!isRecord$6(row)) {
108332
+ if (!isRecord$4(row)) {
107724
108333
  rows.push(row);
107725
108334
  continue;
107726
108335
  }
@@ -107745,7 +108354,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107745
108354
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
107746
108355
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
107747
108356
  case "object": {
107748
- if (!isRecord$6(incoming)) {
108357
+ if (!isRecord$4(incoming)) {
107749
108358
  if (incoming === void 0) return KEEP;
107750
108359
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
107751
108360
  return {
@@ -107753,7 +108362,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
107753
108362
  value: incoming
107754
108363
  };
107755
108364
  }
107756
- const storedObj = isRecord$6(stored) ? stored : {};
108365
+ const storedObj = isRecord$4(stored) ? stored : {};
107757
108366
  return {
107758
108367
  kind: "value",
107759
108368
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -107876,7 +108485,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
107876
108485
  value: items
107877
108486
  };
107878
108487
  }
107879
- if (isRecord$6(v)) {
108488
+ if (isRecord$4(v)) {
107880
108489
  const out = {};
107881
108490
  for (const [k, child] of Object.entries(v)) {
107882
108491
  const s = substitute(child);
@@ -107908,7 +108517,7 @@ var SecretOverwriteRefusedError = class extends Error {
107908
108517
  this.name = "SecretOverwriteRefusedError";
107909
108518
  }
107910
108519
  };
107911
- function isRecord$5(value) {
108520
+ function isRecord$3(value) {
107912
108521
  return typeof value === "object" && value !== null && !Array.isArray(value);
107913
108522
  }
107914
108523
  function resolvedValue(pass, marker) {
@@ -107937,7 +108546,7 @@ function inArray(pass, incoming, stored) {
107937
108546
  return incoming.map((item, index) => {
107938
108547
  const twin = stored[index];
107939
108548
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
107940
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
108549
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
107941
108550
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
107942
108551
  return item;
107943
108552
  });
@@ -107948,7 +108557,7 @@ function inArrayRow(pass, incoming, stored) {
107948
108557
  const twin = stored[key];
107949
108558
  if (isSecretMarker(twin)) {
107950
108559
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
107951
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
108560
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
107952
108561
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
107953
108562
  }
107954
108563
  return out;
@@ -107956,7 +108565,7 @@ function inArrayRow(pass, incoming, stored) {
107956
108565
  async function walk(pass, incoming, stored) {
107957
108566
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
107958
108567
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
107959
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
108568
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
107960
108569
  const out = { ...incoming };
107961
108570
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
107962
108571
  return out;
@@ -107987,7 +108596,7 @@ async function restoreUnchangedSecrets(input) {
107987
108596
  function isJsonEqual(a, b) {
107988
108597
  if (Object.is(a, b)) return true;
107989
108598
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
107990
- if (isRecord$5(a) && isRecord$5(b)) {
108599
+ if (isRecord$3(a) && isRecord$3(b)) {
107991
108600
  const keys = Object.keys(a);
107992
108601
  if (keys.length !== Object.keys(b).length) return false;
107993
108602
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -108011,7 +108620,7 @@ function markerKeysOf(blob, owner) {
108011
108620
  }
108012
108621
  function nodeFromStored(value, owner) {
108013
108622
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
108014
- if (!isRecord$5(value)) return null;
108623
+ if (!isRecord$3(value)) return null;
108015
108624
  const children = /* @__PURE__ */ new Map();
108016
108625
  for (const [key, child] of Object.entries(value)) {
108017
108626
  const node = nodeFromStored(child, owner);
@@ -108508,13 +109117,48 @@ var BaseAddon = class {
108508
109117
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
108509
109118
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
108510
109119
  }
108511
- async runBound(migrations, options) {
109120
+ /**
109121
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
109122
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
109123
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
109124
+ * on every declare).
109125
+ */
109126
+ declareRegistrySwitch(spec) {
109127
+ this.registrySwitchSpec = spec;
109128
+ }
109129
+ registrySwitchSpec = null;
109130
+ registrySwitchBound() {
109131
+ const spec = this.registrySwitchSpec;
109132
+ if (spec === null) return [];
109133
+ const api = this.ctx.migrationApi;
109134
+ if (api === void 0) {
109135
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
109136
+ return [];
109137
+ }
109138
+ return migrationSet([registrySwitchToBodyMigration({
109139
+ addonId: this.ctx.id,
109140
+ date: "2026-11-06",
109141
+ seq: 1e3,
109142
+ initialBody: spec.initialBody
109143
+ })], (a) => registrySwitchPortsOver({
109144
+ api: integrationRowsApiOver(a),
109145
+ records: switchRecordsOverMigrationApi(a),
109146
+ kind: spec.kind
109147
+ })).bind(api);
109148
+ }
109149
+ async runBound(declared, options) {
109150
+ const added = this.registrySwitchBound();
109151
+ const migrations = [...declared, ...added];
109152
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
109153
+ ...options,
109154
+ only: [...options.only, ...added.map((m) => m.meta.id)]
109155
+ };
108512
109156
  const api = this.ctx.api.migrations;
108513
109157
  const report = await runAddonMigrations({
108514
109158
  declareOwner: (input) => api.declareOwner.mutate(input),
108515
109159
  startMigration: (input) => api.startMigration.mutate(input),
108516
109160
  finishMigration: (input) => api.finishMigration.mutate(input)
108517
- }, migrations, this.ctx.logger, options);
109161
+ }, migrations, this.ctx.logger, phased);
108518
109162
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
108519
109163
  return report;
108520
109164
  }
@@ -109587,237 +110231,6 @@ function normalizeAddonInitResult(result) {
109587
110231
  if (Array.isArray(result)) return { providers: result };
109588
110232
  return result;
109589
110233
  }
109590
- var PREFIX = "records/";
109591
- /** The base of every records failure. `detail` is the human part of the message. */
109592
- var RecordsError = class extends Error {
109593
- code;
109594
- detail;
109595
- constructor(code, detail) {
109596
- super(`${PREFIX}${code}: ${detail}`);
109597
- this.name = "RecordsError";
109598
- this.code = code;
109599
- this.detail = detail;
109600
- }
109601
- };
109602
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
109603
- var RevConflictError = class extends RecordsError {
109604
- constructor(detail) {
109605
- super("rev-conflict", detail);
109606
- this.name = "RevConflictError";
109607
- }
109608
- };
109609
- /** The keychain could not store or serve a value: explicit, never an empty string. */
109610
- var RecordSecretUnavailableError = class extends RecordsError {
109611
- constructor(detail) {
109612
- super("secret-unavailable", detail);
109613
- this.name = "RecordSecretUnavailableError";
109614
- }
109615
- };
109616
- var InvalidRecordError = class extends RecordsError {
109617
- constructor(detail) {
109618
- super("invalid-record", detail);
109619
- this.name = "InvalidRecordError";
109620
- }
109621
- };
109622
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
109623
- var DeclarationRefusedError = class extends RecordsError {
109624
- constructor(detail) {
109625
- super("declaration-refused", detail);
109626
- this.name = "DeclarationRefusedError";
109627
- }
109628
- };
109629
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
109630
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
109631
- var RECORD_DATABASES = ["settings", "events"];
109632
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
109633
- var RECORD_CLASSES = [
109634
- "config",
109635
- "ledger",
109636
- "audit",
109637
- "mirror",
109638
- "ephemeral"
109639
- ];
109640
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
109641
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
109642
- var RECORD_BATCH_MAX = 1e3;
109643
- var RECORD_QUERY_MAX = 1e3;
109644
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
109645
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
109646
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
109647
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
109648
- /**
109649
- * Secret fields of a record, addressed the way a Zod schema declares them
109650
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
109651
- * (`auth.accessToken`, `headers[].value`).
109652
- *
109653
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
109654
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
109655
- * key releases exactly that key's secret.
109656
- *
109657
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
109658
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
109659
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
109660
- * leaf names its element: `headers[X-Api].value`.
109661
- *
109662
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
109663
- */
109664
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
109665
- function parseSecretPath(path) {
109666
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
109667
- return path.split(".").map((raw) => {
109668
- const each = raw.endsWith("[]");
109669
- const map = raw.endsWith("{}");
109670
- const key = each || map ? raw.slice(0, -2) : raw;
109671
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
109672
- return {
109673
- key,
109674
- each,
109675
- map
109676
- };
109677
- });
109678
- }
109679
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
109680
- function secretArrayPrefixes(path) {
109681
- const segments = parseSecretPath(path);
109682
- const prefixes = [];
109683
- const walked = [];
109684
- for (const segment of segments) {
109685
- walked.push(segment.key);
109686
- if (segment.each) prefixes.push(walked.join("."));
109687
- }
109688
- return prefixes;
109689
- }
109690
- function isRecord$4(value) {
109691
- return typeof value === "object" && value !== null && !Array.isArray(value);
109692
- }
109693
- function elementId(element, idKey, declared, prefix) {
109694
- const id = isRecord$4(element) ? element[idKey] : void 0;
109695
- if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
109696
- return id;
109697
- }
109698
- /**
109699
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
109700
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
109701
- * result is a new body, `data` is untouched.
109702
- */
109703
- var REMOVE_LEAF = Symbol("remove-leaf");
109704
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
109705
- if (!isRecord$4(node)) return node;
109706
- const segment = segments[index];
109707
- if (segment === void 0) return node;
109708
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
109709
- const child = node[segment.key];
109710
- const keys = [...walkedKeys, segment.key];
109711
- const last = index === segments.length - 1;
109712
- if (segment.each) {
109713
- if (!Array.isArray(child)) return node;
109714
- const prefix = keys.join(".");
109715
- const idKey = arrayKeys[prefix];
109716
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
109717
- const mapped = child.map((element) => {
109718
- const id = elementId(element, idKey, declared, prefix);
109719
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
109720
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
109721
- });
109722
- return {
109723
- ...node,
109724
- [segment.key]: mapped
109725
- };
109726
- }
109727
- if (segment.map) {
109728
- if (!isRecord$4(child)) return node;
109729
- const kept = Object.entries(child).map(([mapKey, value]) => {
109730
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
109731
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
109732
- return [mapKey, visit({
109733
- declared,
109734
- concrete,
109735
- value
109736
- })];
109737
- }).filter(([, value]) => value !== REMOVE_LEAF);
109738
- return {
109739
- ...node,
109740
- [segment.key]: Object.fromEntries(kept)
109741
- };
109742
- }
109743
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
109744
- if (last) {
109745
- const replacement = visit({
109746
- declared,
109747
- concrete,
109748
- value: child
109749
- });
109750
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
109751
- return {
109752
- ...node,
109753
- [segment.key]: replacement
109754
- };
109755
- }
109756
- return {
109757
- ...node,
109758
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
109759
- };
109760
- }
109761
- /** Replace/remove every present secret leaf; returns a NEW body. */
109762
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
109763
- let current = data;
109764
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
109765
- return current;
109766
- }
109767
- /** Every present secret leaf, read-only. */
109768
- function collectSecretLeaves(data, paths, arrayKeys) {
109769
- const found = [];
109770
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
109771
- found.push(leaf);
109772
- return leaf.value;
109773
- });
109774
- return found;
109775
- }
109776
- /**
109777
- * The keychain collection name a kind's secrets live under. Prefixed so a
109778
- * record's refs never collide with the refs a legacy collection of the same name
109779
- * already holds during an adoption.
109780
- */
109781
- function recordSecretCollection(kind) {
109782
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
109783
- }
109784
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
109785
- function recordSecretRef(owner, kind, rowId, concretePath) {
109786
- return buildSecretRef({
109787
- owner,
109788
- scope: {
109789
- kind: "row",
109790
- collection: recordSecretCollection(kind),
109791
- rowId
109792
- },
109793
- fieldPath: concretePath
109794
- });
109795
- }
109796
- /**
109797
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
109798
- * keychain ref (`set: true`), never the value and no longer the bare redaction
109799
- * token. The form hands it to the secret field, which reveals the value by ref
109800
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
109801
- * stored secret (the records door reads a view as KEEP).
109802
- *
109803
- * ONE implementation for the entries service and for every addon that serves
109804
- * its own instances (`RecordIntegrationInstances`).
109805
- */
109806
- function isRecord$3(value) {
109807
- return typeof value === "object" && value !== null && !Array.isArray(value);
109808
- }
109809
- function secretViewsOf(owner, kind, id, decl, data) {
109810
- if (decl.secretPaths.length === 0) return data;
109811
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
109812
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
109813
- return {
109814
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
109815
- v: 1,
109816
- set: true
109817
- };
109818
- });
109819
- return isRecord$3(shown) ? shown : data;
109820
- }
109821
110234
  /**
109822
110235
  * The share-view scope kinds a share-link token can carry. The hub mints
109823
110236
  * and validates them (`ShareViewGrantSchema` builds its
@@ -110071,6 +110484,7 @@ function defineRecordKinds(specs) {
110071
110484
  function entryBody(shape) {
110072
110485
  return object({
110073
110486
  name: string().min(1),
110487
+ enabled: boolean().optional(),
110074
110488
  ...shape
110075
110489
  });
110076
110490
  }
@@ -112023,6 +112437,10 @@ Object.freeze({
112023
112437
  "all",
112024
112438
  "one"
112025
112439
  ]
112440
+ },
112441
+ {
112442
+ "path": "positionUpdatedAt",
112443
+ "valueType": "number"
112026
112444
  }
112027
112445
  ],
112028
112446
  "meter": [{
@@ -112277,22 +112695,6 @@ Object.freeze({
112277
112695
  "path": "pumpRunning",
112278
112696
  "valueType": "boolean"
112279
112697
  },
112280
- {
112281
- "path": "lastDrink",
112282
- "valueType": "number"
112283
- },
112284
- {
112285
- "path": "currentHourDrink",
112286
- "valueType": "number"
112287
- },
112288
- {
112289
- "path": "last24hDrink",
112290
- "valueType": "number"
112291
- },
112292
- {
112293
- "path": "todayDrink",
112294
- "valueType": "number"
112295
- },
112296
112698
  {
112297
112699
  "path": "error",
112298
112700
  "valueType": "string"
@@ -112858,6 +113260,60 @@ Object.freeze({
112858
113260
  }
112859
113261
  ]
112860
113262
  });
113263
+ Object.freeze({
113264
+ "actions": { "run": 363e4 },
113265
+ "audio-analyzer": { "classify": 3e4 },
113266
+ "custom-model-registry": { "importModelBundle": 18e5 },
113267
+ "database-snapshot": { "writeSnapshot": 18e5 },
113268
+ "device-manager": {
113269
+ "migrateDevice": 72e4,
113270
+ "runDiscoverySweep": 12e4
113271
+ },
113272
+ "device-provider": { "reloadDevice": 18e4 },
113273
+ "llm": {
113274
+ "generate": 6e5,
113275
+ "generateVision": 6e5,
113276
+ "testProfile": 6e5
113277
+ },
113278
+ "llm-runtime": {
113279
+ "complete": 6e5,
113280
+ "completeApple": 6e5,
113281
+ "ensureStarted": 6e5,
113282
+ "installModel": 36e5
113283
+ },
113284
+ "local-network": { "scanNetwork": 9e4 },
113285
+ "model-convert": { "convert": 6e5 },
113286
+ "pipeline-analytics": {
113287
+ "addRetrainFrameFromRecording": 6e4,
113288
+ "offerRetrainArchive": 12e4,
113289
+ "proposeRetrainAnnotationsWithLlm": 18e4,
113290
+ "resolveRetrainTrainingCorpus": 6e4,
113291
+ "writeRetrainArchive": 36e5
113292
+ },
113293
+ "server-management": { "applyServerUpdate": 96e4 },
113294
+ "terminal-session": { "pullOutput": 15e3 },
113295
+ "training": {
113296
+ "canaryResult": 12e4,
113297
+ "cancelJob": 12e4,
113298
+ "planJob": 6e4,
113299
+ "registerResult": 18e5,
113300
+ "rollbackCanary": 12e4,
113301
+ "startJob": 12e4,
113302
+ "startJobBatch": 12e4
113303
+ },
113304
+ "training-provider": {
113305
+ "cancelJob": 6e4,
113306
+ "cleanupJob": 3e5,
113307
+ "getJob": 6e4,
113308
+ "listJobEvents": 6e4,
113309
+ "listJobs": 12e4,
113310
+ "offerArtifact": 3e5,
113311
+ "readResult": 3e5,
113312
+ "submitJob": 18e5,
113313
+ "uploadDataset": 72e5,
113314
+ "validateCredentials": 3e4
113315
+ }
113316
+ });
112861
113317
  object({
112862
113318
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
112863
113319
  params: record(string(), union([string(), number()])).optional()
@@ -112901,7 +113357,7 @@ function sleep(ms) {
112901
113357
  return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
112902
113358
  }
112903
113359
  //#endregion
112904
- //#region ../types/dist/composition-pOHbTzRB.mjs
113360
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
112905
113361
  /**
112906
113362
  * The ffmpeg build every CamStack node downloads, per platform and arch.
112907
113363
  *
@@ -113205,7 +113661,7 @@ var table = {
113205
113661
  },
113206
113662
  dwell: {
113207
113663
  minArgs: 3,
113208
- maxArgs: 3,
113664
+ maxArgs: 4,
113209
113665
  apply: () => {
113210
113666
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
113211
113667
  }
@@ -114062,6 +114518,17 @@ var NodeColorIdSchema = _enum([
114062
114518
  "node-g",
114063
114519
  "node-h"
114064
114520
  ]);
114521
+ //#endregion
114522
+ //#region ../types/dist/index.mjs
114523
+ /**
114524
+ * The `smtp-inbound` broker kind (D999): a mailbox a device can send mail to.
114525
+ *
114526
+ * The `broker` cap carries these as `Record<string, unknown>` on the wire; the
114527
+ * provider and its consumers parse them with the schemas below at BOTH ends, so
114528
+ * the shape is declared once.
114529
+ */
114530
+ /** The broker kind tag. */
114531
+ var SMTP_INBOUND_KIND = "smtp-inbound";
114065
114532
  /** The id the first mailbox is minted under (adopt-id), so a consumer can find it again. */
114066
114533
  var SMTP_INBOUND_DEFAULT_ID = "smtp-inbound-default";
114067
114534
  var SMTP_INBOUND_DEFAULT_PORT = 2525;
@@ -114258,212 +114725,6 @@ var IntegrationInstanceRefSchema = object({
114258
114725
  ]),
114259
114726
  candidateStableId: string().optional()
114260
114727
  });
114261
- /**
114262
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
114263
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
114264
- *
114265
- * Every instance is one record of the addon's own kind, keyed by the
114266
- * `integrations` registry id. The records door does the secret work: a field the
114267
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
114268
- * deleting the row deletes the secret, and one row's value is never another's.
114269
- *
114270
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
114271
- * token or the view the form was given KEEP the stored secret;
114272
- * `{ $secretClear: true }` clears it; any other string replaces it.
114273
- */
114274
- /** The most instances one addon lists (an integrations page, not a table). */
114275
- var INSTANCES_LIST_MAX = 1e3;
114276
- /** The keys of the kind's secret fields that sit at the top level of the body. */
114277
- function topLevelSecretKeys(paths) {
114278
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
114279
- }
114280
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
114281
- function secretMapKeys(paths) {
114282
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
114283
- }
114284
- /**
114285
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
114286
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
114287
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
114288
- */
114289
- function secretMapPatch(value) {
114290
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
114291
- const out = {};
114292
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
114293
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
114294
- return Object.keys(out).length > 0 ? out : null;
114295
- }
114296
- /** Does the kind's body schema carry an `enabled` field? */
114297
- function declaresEnabled(kind) {
114298
- const json = toJSONSchema(kind.schema, {
114299
- unrepresentable: "any",
114300
- io: "input"
114301
- });
114302
- const properties = Reflect.get(json, "properties");
114303
- return typeof properties === "object" && properties !== null && "enabled" in properties;
114304
- }
114305
- var RecordIntegrationInstances = class {
114306
- records;
114307
- kind;
114308
- hooks;
114309
- handle;
114310
- secretKeys;
114311
- secretMaps;
114312
- nameField;
114313
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
114314
- registryOwnsEnabled;
114315
- constructor(records, kind, hooks) {
114316
- this.records = records;
114317
- this.kind = kind;
114318
- this.hooks = hooks;
114319
- this.handle = records.kind(kind);
114320
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
114321
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
114322
- this.nameField = kind.declaration.entry?.nameField ?? "name";
114323
- this.registryOwnsEnabled = hooks.description.role === "devices";
114324
- if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
114325
- }
114326
- /**
114327
- * One instance read for the addon's own runtime; null when absent. When the keychain is
114328
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
114329
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
114330
- */
114331
- async readResolved(id) {
114332
- try {
114333
- const record = await this.handle.getResolved(id);
114334
- return record === null ? null : {
114335
- id,
114336
- body: record.data,
114337
- enabled: record.data.enabled !== false,
114338
- secrets: "resolved"
114339
- };
114340
- } catch (err) {
114341
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
114342
- const stored = await this.handle.get(id);
114343
- if (stored === null) return null;
114344
- return {
114345
- id,
114346
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
114347
- enabled: stored.data.enabled !== false,
114348
- secrets: "unavailable"
114349
- };
114350
- }
114351
- }
114352
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
114353
- async getResolved(id) {
114354
- return (await this.readResolved(id))?.body ?? null;
114355
- }
114356
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
114357
- async listResolved() {
114358
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
114359
- const out = [];
114360
- for (const record of page.records) {
114361
- const read = await this.readResolved(record.id);
114362
- if (read !== null) out.push(read);
114363
- }
114364
- return out;
114365
- }
114366
- viewOf(record) {
114367
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
114368
- const rawName = record.data[this.nameField];
114369
- const kind = this.hooks.kindOf?.(record.data);
114370
- const health = this.hooks.health?.(record.data, record.id);
114371
- return {
114372
- id: record.id,
114373
- name: typeof rawName === "string" ? rawName : record.id,
114374
- configured: this.hooks.configured(record.data),
114375
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
114376
- formValues: shown,
114377
- ...kind !== void 0 ? { kind } : {},
114378
- ...health?.status !== void 0 ? { status: health.status } : {},
114379
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
114380
- };
114381
- }
114382
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
114383
- ...this.hooks.description,
114384
- mintsId: true
114385
- };
114386
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
114387
- listInstances = async () => {
114388
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
114389
- };
114390
- getInstance = async ({ id }) => {
114391
- const record = await this.handle.get(id);
114392
- return record === null ? null : this.viewOf(record);
114393
- };
114394
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
114395
- createInstance = async ({ id, name, kind, values }) => {
114396
- const minted = id ?? this.hooks.mintId?.({
114397
- name,
114398
- ...kind !== void 0 ? { kind } : {}
114399
- });
114400
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
114401
- await this.handle.put({
114402
- id: minted,
114403
- data: this.hooks.initialBody(name, kind)
114404
- }, { ifRev: 0 });
114405
- const patch = this.patchOf(values ?? {});
114406
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
114407
- await this.hooks.onChanged?.(minted, "created");
114408
- return { id: minted };
114409
- };
114410
- updateInstance = async ({ id, name, values }) => {
114411
- const patch = this.patchOf(values);
114412
- if (name !== void 0) patch[this.nameField] = name;
114413
- await this.handle.patch(id, patch);
114414
- await this.hooks.onChanged?.(id, "updated");
114415
- return { ok: true };
114416
- };
114417
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
114418
- patchOf(values) {
114419
- const patch = {};
114420
- for (const [key, value] of Object.entries(values)) {
114421
- if (value === void 0) continue;
114422
- if (this.secretMaps.has(key)) {
114423
- const entries = secretMapPatch(value);
114424
- if (entries !== null) patch[key] = entries;
114425
- } else if (!this.secretKeys.has(key)) patch[key] = value;
114426
- else if (isSecretClear(value)) patch[key] = null;
114427
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
114428
- }
114429
- return patch;
114430
- }
114431
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
114432
- setInstanceEnabled = async ({ id, enabled }) => {
114433
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
114434
- await this.handle.patch(id, { enabled });
114435
- await this.hooks.onChanged?.(id, "enabled");
114436
- return { ok: true };
114437
- };
114438
- /** The row and its keychain refs go together (the records door). */
114439
- deleteInstance = async ({ id }) => {
114440
- await this.handle.delete(id);
114441
- await this.hooks.onChanged?.(id, "deleted");
114442
- return { ok: true };
114443
- };
114444
- testInstance = async (input) => {
114445
- if (this.hooks.test === void 0) return {
114446
- success: false,
114447
- status: "unsupported",
114448
- error: "This integration declares no connection test"
114449
- };
114450
- return this.hooks.test(input);
114451
- };
114452
- /** The flat provider object to hand to `registerProvider`. */
114453
- toProvider() {
114454
- return {
114455
- describe: this.describe,
114456
- instanceFormSchema: this.instanceFormSchema,
114457
- listInstances: this.listInstances,
114458
- getInstance: this.getInstance,
114459
- createInstance: this.createInstance,
114460
- updateInstance: this.updateInstance,
114461
- setInstanceEnabled: this.setInstanceEnabled,
114462
- deleteInstance: this.deleteInstance,
114463
- testInstance: this.testInstance
114464
- };
114465
- }
114466
- };
114467
114728
  var EncodeProfileSchema = object({
114468
114729
  video: object({
114469
114730
  codec: _enum([
@@ -121528,31 +121789,21 @@ var APPLIANCE_CAP_VOCABULARY = {
121528
121789
  "pet-fountain": {
121529
121790
  scope: "device",
121530
121791
  noun: t("Pet fountain", "Fontana per animali"),
121531
- actions: [
121532
- {
121533
- id: "petFountain.pumpOn",
121534
- method: "setPump",
121535
- label: t("Pump on", "Pompa accesa"),
121536
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
121537
- icon: "play",
121538
- args: { on: true }
121539
- },
121540
- {
121541
- id: "petFountain.pumpOff",
121542
- method: "setPump",
121543
- label: t("Pump off", "Pompa spenta"),
121544
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
121545
- icon: "square",
121546
- args: { on: false }
121547
- },
121548
- {
121549
- id: "petFountain.resetDailyConsumption",
121550
- method: "resetDailyConsumption",
121551
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
121552
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
121553
- icon: "rotate-ccw"
121554
- }
121555
- ],
121792
+ actions: [{
121793
+ id: "petFountain.pumpOn",
121794
+ method: "setPump",
121795
+ label: t("Pump on", "Pompa accesa"),
121796
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
121797
+ icon: "play",
121798
+ args: { on: true }
121799
+ }, {
121800
+ id: "petFountain.pumpOff",
121801
+ method: "setPump",
121802
+ label: t("Pump off", "Pompa spenta"),
121803
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
121804
+ icon: "square",
121805
+ args: { on: false }
121806
+ }],
121556
121807
  state: [{
121557
121808
  kind: "boolean",
121558
121809
  field: "empty",
@@ -145506,8 +145757,15 @@ var ActionInputSchema = object({
145506
145757
  var ActionRunOriginSchema = object({
145507
145758
  /** The automation block whose step started it. */
145508
145759
  blockId: string().min(1).optional() });
145509
- /** `started` = the caller did not ask to wait. */
145510
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
145760
+ /**
145761
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
145762
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
145763
+ */
145764
+ var ActionRunOutcomeSchema = union([
145765
+ AutomationRunOutcomeSchema,
145766
+ literal("started"),
145767
+ literal("timed-out")
145768
+ ]);
145511
145769
  var ActionRunResultSchema = object({
145512
145770
  runId: string().min(1),
145513
145771
  outcome: ActionRunOutcomeSchema,
@@ -146029,6 +146287,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146029
146287
  kind: "mutation",
146030
146288
  auth: "admin"
146031
146289
  });
146290
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
146291
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
146032
146292
  /**
146033
146293
  * actions — the ONE surface for runnable actions, for the UI and for
146034
146294
  * automations. Provided by the core-blocks builtin on the hub.
@@ -146047,6 +146307,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146047
146307
  * An admin, and an in-process caller (an automation block), may run any action.
146048
146308
  * Every refusal is typed (`[not-linked] …`) and logged.
146049
146309
  *
146310
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
146311
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
146312
+ * `wait` steps alone add up to more is refused at create/update
146313
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
146314
+ * waited call (an automation step) is never cut by the 60 s transport default.
146315
+ *
146050
146316
  * A second `run` of an action that is already running is REFUSED — traced and
146051
146317
  * logged — never queued.
146052
146318
  */
@@ -146073,7 +146339,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
146073
146339
  role: "viewer",
146074
146340
  auth: "protected",
146075
146341
  kind: "mutation",
146076
- caller: "required"
146342
+ caller: "required",
146343
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
146077
146344
  }), method(ActionIdInput, _void(), {
146078
146345
  kind: "mutation",
146079
146346
  auth: "admin"
@@ -151100,6 +151367,9 @@ var MediaPlayerStatusSchema = object({
151100
151367
  /** Repeat mode. Null when no repeat surface.
151101
151368
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
151102
151369
  repeat: MediaPlayerRepeatSchema.nullable(),
151370
+ /** Ms epoch when `position` was read from the device. Null when the driver
151371
+ * does not say; a UI that advances the position while playing counts from it. */
151372
+ positionUpdatedAt: number().nullable().default(null),
151103
151373
  /** Ms epoch when the slice was last updated. */
151104
151374
  lastChangedAt: number()
151105
151375
  });
@@ -151735,7 +152005,9 @@ var ThresholdTransformDraftSchema = object({
151735
152005
  comparison: _enum(["gte", "lte"]),
151736
152006
  threshold: number(),
151737
152007
  startDwellMs: number().nonnegative(),
151738
- stopDwellMs: number().nonnegative()
152008
+ stopDwellMs: number().nonnegative(),
152009
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
152010
+ minSamples: number().int().min(1).optional()
151739
152011
  });
151740
152012
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
151741
152013
  IdentityTransformDraftSchema,
@@ -157665,6 +157937,7 @@ var IntegrationWithStateSchema = object({
157665
157937
  id: string(),
157666
157938
  addonId: string(),
157667
157939
  name: string(),
157940
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157668
157941
  enabled: boolean(),
157669
157942
  info: record(string(), unknown()).readonly(),
157670
157943
  /** The discovery candidate this integration was set up from (D984). */
@@ -157677,6 +157950,7 @@ var IntegrationLiteSchema = object({
157677
157950
  id: string(),
157678
157951
  addonId: string(),
157679
157952
  name: string(),
157953
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
157680
157954
  enabled: boolean(),
157681
157955
  info: record(string(), unknown()).readonly(),
157682
157956
  /** The discovery candidate this integration was set up from (D984). */
@@ -157776,7 +158050,6 @@ var TestConnectionResultSchema = object({
157776
158050
  var CreateIntegrationInputSchema = object({
157777
158051
  addonId: string(),
157778
158052
  name: string(),
157779
- enabled: boolean().optional(),
157780
158053
  info: record(string(), unknown()).optional(),
157781
158054
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
157782
158055
  originStableId: string().optional(),
@@ -157785,6 +158058,11 @@ var CreateIntegrationInputSchema = object({
157785
158058
  var UpdateIntegrationInputSchema = object({
157786
158059
  id: string(),
157787
158060
  name: string().optional(),
158061
+ /**
158062
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
158063
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
158064
+ * integration is switched through `integration-instances.setInstanceEnabled`.
158065
+ */
157788
158066
  enabled: boolean().optional(),
157789
158067
  info: record(string(), unknown()).optional()
157790
158068
  });
@@ -157832,7 +158110,7 @@ var IntegrationInstanceIdSchema = string().min(1);
157832
158110
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
157833
158111
  /**
157834
158112
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
157835
- * instance is an integration that brings devices (the registry owns its on/off switch);
158113
+ * instance is an integration that brings devices (its record body owns the on/off switch);
157836
158114
  * `services`: a connection configured from the addon's own function page, never listed on
157837
158115
  * Integrations.
157838
158116
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -157875,18 +158153,38 @@ var IntegrationInstanceKindSchema = object({
157875
158153
  /** Relative hub path to disconnect that account. */
157876
158154
  disconnectPath: string().min(1).optional()
157877
158155
  });
158156
+ /**
158157
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
158158
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
158159
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
158160
+ * instance and its candidates are claimed by it.
158161
+ */
158162
+ var IntegrationInstanceDiscoverySchema = object({
158163
+ mode: _enum([
158164
+ "none",
158165
+ "lan",
158166
+ "account"
158167
+ ]),
158168
+ scopedToInstance: boolean()
158169
+ });
158170
+ /**
158171
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
158172
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
158173
+ * The hub indexes these so the target's delete is refused while a link names it.
158174
+ */
158175
+ var IntegrationInstanceLinkSchema = object({
158176
+ kind: string().min(1),
158177
+ field: string().min(1),
158178
+ to: object({
158179
+ cap: string().min(1),
158180
+ kind: string().min(1).optional()
158181
+ })
158182
+ });
157878
158183
  var IntegrationInstanceDescriptionSchema = object({
157879
158184
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
157880
158185
  role: IntegrationInstanceRoleSchema,
157881
158186
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
157882
- discovery: object({
157883
- mode: _enum([
157884
- "none",
157885
- "lan",
157886
- "account"
157887
- ]),
157888
- scopedToInstance: boolean()
157889
- }).optional(),
158187
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
157890
158188
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
157891
158189
  instanceMode: IntegrationInstanceModeSchema,
157892
158190
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -157907,7 +158205,9 @@ var IntegrationInstanceDescriptionSchema = object({
157907
158205
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
157908
158206
  * send an id (the UI then mints an opaque one).
157909
158207
  */
157910
- mintsId: boolean().optional()
158208
+ mintsId: boolean().optional(),
158209
+ /** The links to other instances the provider's kinds declare; absent means none. */
158210
+ links: array(IntegrationInstanceLinkSchema).optional()
157911
158211
  });
157912
158212
  var IntegrationInstanceStatusSchema = object({
157913
158213
  state: _enum([
@@ -157927,8 +158227,8 @@ var IntegrationInstanceSchema = object({
157927
158227
  configured: boolean(),
157928
158228
  /**
157929
158229
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
157930
- * so a row written before the field existed is on). Absent when the `integrations` registry
157931
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
158230
+ * so a row written before the field existed is on). The same for every role, `devices` included:
158231
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
157932
158232
  */
157933
158233
  enabled: boolean().optional(),
157934
158234
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -157978,7 +158278,8 @@ var integrationInstancesCapability = {
157978
158278
  auth: "admin"
157979
158279
  }),
157980
158280
  /**
157981
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
158281
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
158282
+ * initial body. A row control, not a form field: `updateInstance.values` is the
157982
158283
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
157983
158284
  */
157984
158285
  setInstanceEnabled: method(object({
@@ -161062,6 +161363,8 @@ var MigrationIntegrationSchema = object({
161062
161363
  addonId: string(),
161063
161364
  name: string(),
161064
161365
  info: Rows,
161366
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
161367
+ enabled: boolean().optional(),
161065
161368
  originStableId: string().optional()
161066
161369
  });
161067
161370
  var MigrationDeviceSchema = object({
@@ -171257,14 +171560,6 @@ var PetFountainStatusSchema = object({
171257
171560
  empty: boolean().nullable(),
171258
171561
  /** True while the pump is running. Null while unknown. */
171259
171562
  pumpRunning: boolean().nullable(),
171260
- /** Water drunk in the last drink, in litres. */
171261
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
171262
- /** Water drunk in the current hour, in litres. */
171263
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
171264
- /** Water drunk over the last 24 hours (rolling), in litres. */
171265
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
171266
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
171267
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
171268
171563
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
171269
171564
  error: string().nullable(),
171270
171565
  /** Ms epoch when the slice was last refreshed. */
@@ -171277,21 +171572,15 @@ var petFountainCapability = {
171277
171572
  deviceNative: true,
171278
171573
  mode: "singleton",
171279
171574
  deviceTypes: [DeviceType.PetFountain],
171280
- methods: {
171281
- /** Start or stop the pump. */
171282
- setPump: method(object({
171283
- deviceId: DeviceIdSchema$1,
171284
- on: boolean()
171285
- }), _void(), {
171286
- kind: "mutation",
171287
- auth: "protected"
171288
- }),
171289
- /** Clear the rolling daily consumption counters on the device. */
171290
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
171291
- kind: "mutation",
171292
- auth: "protected"
171293
- })
171294
- },
171575
+ methods: {
171576
+ /** Start or stop the pump. */
171577
+ setPump: method(object({
171578
+ deviceId: DeviceIdSchema$1,
171579
+ on: boolean()
171580
+ }), _void(), {
171581
+ kind: "mutation",
171582
+ auth: "protected"
171583
+ }) },
171295
171584
  status: {
171296
171585
  schema: PetFountainStatusSchema,
171297
171586
  kind: "push"
@@ -171315,14 +171604,6 @@ var petFountainCapability = {
171315
171604
  waterVolume: {
171316
171605
  kind: "gauge",
171317
171606
  unit: "L"
171318
- },
171319
- todayDrink: {
171320
- kind: "gauge",
171321
- unit: "L"
171322
- },
171323
- last24hDrink: {
171324
- kind: "gauge",
171325
- unit: "L"
171326
171607
  }
171327
171608
  } }
171328
171609
  };
@@ -191038,13 +191319,6 @@ Object.freeze({
191038
191319
  access: "view",
191039
191320
  role: "viewer"
191040
191321
  },
191041
- "petFountain.resetDailyConsumption": {
191042
- capName: "pet-fountain",
191043
- capScope: "device",
191044
- addonId: null,
191045
- access: "delete",
191046
- role: "viewer"
191047
- },
191048
191322
  "petFountain.setPump": {
191049
191323
  capName: "pet-fountain",
191050
191324
  capScope: "device",
@@ -197593,11 +197867,6 @@ Object.freeze({
197593
197867
  form: "single",
197594
197868
  optional: false
197595
197869
  }],
197596
- "petFountain.resetDailyConsumption": [{
197597
- name: "deviceId",
197598
- form: "single",
197599
- optional: false
197600
- }],
197601
197870
  "petFountain.setPump": [{
197602
197871
  name: "deviceId",
197603
197872
  form: "single",
@@ -200392,7 +200661,6 @@ object({
200392
200661
  delay: number().nonnegative().optional(),
200393
200662
  commands: record(string(), unknown())
200394
200663
  });
200395
- entryBody({ brokerId: string() });
200396
200664
  //#endregion
200397
200665
  //#region src/clips/clip-prefetch.ts
200398
200666
  /** The longest a device may stay quiet after refusals, whatever its interval. */
@@ -212895,6 +213163,10 @@ var ReolinkCamera = class ReolinkCamera extends BaseDevice {
212895
213163
  const host = this.config.get("host");
212896
213164
  return typeof host === "string" && host.length > 0 ? host : null;
212897
213165
  }
213166
+ /** The integration this camera belongs to, or `null` when it names none. */
213167
+ get integrationId() {
213168
+ return this.hubIntegrationId();
213169
+ }
212898
213170
  /** The integration (one NVR / Home Hub, D985) this camera was adopted from, or `null`. */
212899
213171
  hubIntegrationId() {
212900
213172
  const id = this.config.get("integrationId");
@@ -220869,6 +221141,20 @@ var SMTP_BROKER_ADDON_ID = "smtp-nodemailer";
220869
221141
  /** Who this addon is, among the subscribers of a mailbox. */
220870
221142
  var REOLINK_SUBSCRIBER_ID = "provider-reolink";
220871
221143
  var MAILBOX_NAME = "Camera mailbox";
221144
+ /** What an integration's `mailboxId` points at: an `smtp-inbound` instance of the `broker` cap (D1013). */
221145
+ var SMTP_MAILBOX_LINK = {
221146
+ cap: "broker",
221147
+ kind: SMTP_INBOUND_KIND
221148
+ };
221149
+ /** The body field of an integration record that names its camera mailbox; empty or absent when none. */
221150
+ var MAILBOX_LINK_FIELD = "mailboxId";
221151
+ /**
221152
+ * The link field of the integration record. The bridge fills it (an integration whose standalone
221153
+ * cameras mail the mailbox links to it), so the hub refuses to delete a mailbox that is in use.
221154
+ */
221155
+ function mailboxLinkField() {
221156
+ return optionalLinkField(SMTP_MAILBOX_LINK);
221157
+ }
220872
221158
  var RECIPIENT_PREFIX = "cam-";
220873
221159
  /**
220874
221160
  * The real port: the mailboxes are `integration-instances` of the SMTP addon (the kind of its
@@ -221022,20 +221308,54 @@ var EmailPushBridge = class {
221022
221308
  const recipients = this.recipients();
221023
221309
  if (recipients.length === 0) {
221024
221310
  if (this.brokerId !== null && this.subscriptionId !== null) await this.deps.port.unsubscribe(this.brokerId, this.subscriptionId);
221311
+ if (this.brokerId !== null) await this.syncLinks(this.brokerId, /* @__PURE__ */ new Set());
221025
221312
  this.subscriptionId = null;
221026
221313
  this.declared = null;
221027
221314
  return;
221028
221315
  }
221029
- const key = recipients.join(",");
221316
+ const owners = this.linkOwners();
221317
+ const key = `${recipients.join(",")}|${[...owners].sort().join(",")}`;
221030
221318
  if (!force && this.declared === key && this.subscriptionId !== null) return;
221031
221319
  const brokerId = await this.ensureMailbox();
221032
221320
  await this.seedBaseline(brokerId);
221033
221321
  const { subscriptionId } = await this.deps.port.subscribe(brokerId, recipients);
221034
221322
  this.brokerId = brokerId;
221035
221323
  this.subscriptionId = subscriptionId;
221036
- this.declared = key;
221324
+ this.declared = await this.syncLinks(brokerId, owners) ? key : null;
221037
221325
  await this.reconcile();
221038
221326
  }
221327
+ /** The integrations whose standalone cameras mail the mailbox: they link to it. */
221328
+ linkOwners() {
221329
+ const owners = /* @__PURE__ */ new Set();
221330
+ for (const cam of this.deps.listCameras()) if (cam.isEmailPushEligible && cam.integrationId !== null) owners.add(cam.integrationId);
221331
+ return owners;
221332
+ }
221333
+ /**
221334
+ * Make the `mailboxId` links say who uses the mailbox: `owners` link to it, no other
221335
+ * integration does. Idempotent, so an install whose mailbox already exists is filled from it
221336
+ * (the mailbox is re-adopted by `ensureMailbox`) with nothing stored beforehand. False when the
221337
+ * links could not be written: the caller retries at the next sync.
221338
+ */
221339
+ async syncLinks(brokerId, owners) {
221340
+ try {
221341
+ const rows = await this.deps.links.list();
221342
+ for (const row of rows) {
221343
+ const wanted = owners.has(row.id) ? brokerId : "";
221344
+ if (row.mailboxId !== wanted) await this.deps.links.set(row.id, wanted);
221345
+ }
221346
+ for (const owner of owners) if (!rows.some((row) => row.id === owner)) this.deps.logger.warn("email-push: an integration with email-push cameras has no record to link the mailbox from", { meta: {
221347
+ integrationId: owner,
221348
+ brokerId
221349
+ } });
221350
+ return true;
221351
+ } catch (err) {
221352
+ this.deps.logger.warn("email-push: the camera mailbox links could not be written", { meta: {
221353
+ brokerId,
221354
+ error: errMsg(err)
221355
+ } });
221356
+ return false;
221357
+ }
221358
+ }
221039
221359
  /**
221040
221360
  * What the mailbox retains from BEFORE this subscription is old news (a restart of this addon
221041
221361
  * must not re-fire a quarter hour of alarms). Nothing for our recipients is accepted before the
@@ -221184,6 +221504,126 @@ var EmailPushBridge = class {
221184
221504
  function pickMailbox(list) {
221185
221505
  return list.find((b) => b.id === "smtp-inbound-default")?.id ?? list[0]?.id ?? null;
221186
221506
  }
221507
+ var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221508
+ title: "Reolink integrations",
221509
+ schema: entryBody({
221510
+ host: string().nullish(),
221511
+ port: number().int().min(1).max(65535).nullish(),
221512
+ rtspPort: number().int().min(1).max(65535).nullish(),
221513
+ username: string().nullish(),
221514
+ password: string().optional().meta({ secret: true }),
221515
+ transport: _enum(["tcp", "udp"]).nullish(),
221516
+ uid: string().nullish(),
221517
+ debugGeneral: boolean().nullish(),
221518
+ debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish(),
221519
+ mailboxId: mailboxLinkField()
221520
+ }),
221521
+ writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221522
+ });
221523
+ /** Every kind this addon declares, keyed by its name. */
221524
+ var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221525
+ /** The record body as the connection form's flat values: no name, no unset keys. */
221526
+ function hubSettingsOf(body) {
221527
+ const out = {};
221528
+ for (const [key, value] of Object.entries(body)) {
221529
+ if (key === "name" || value === null || value === void 0) continue;
221530
+ out[key] = value;
221531
+ }
221532
+ return out;
221533
+ }
221534
+ /**
221535
+ * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221536
+ * its password: that is `password-locked`, never an empty password (D49).
221537
+ */
221538
+ function hubConnectionOf(resolved) {
221539
+ const read = readHubConnection(hubSettingsOf(resolved.body));
221540
+ return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221541
+ }
221542
+ /**
221543
+ * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221544
+ * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221545
+ */
221546
+ async function readHubConnections(instances, integrations) {
221547
+ const out = [];
221548
+ for (const integration of integrations) {
221549
+ const resolved = await instances.readResolved(integration.id);
221550
+ out.push({
221551
+ id: integration.id,
221552
+ name: integration.name,
221553
+ read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221554
+ });
221555
+ }
221556
+ return out;
221557
+ }
221558
+ function buildReolinkInstances(records, deps) {
221559
+ return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221560
+ description: {
221561
+ role: "devices",
221562
+ discovery: {
221563
+ mode: "lan",
221564
+ scopedToInstance: false
221565
+ },
221566
+ instanceMode: "multiple",
221567
+ kind: "connection",
221568
+ canTest: false
221569
+ },
221570
+ formSchema: () => buildHubInstanceSchema(),
221571
+ initialBody: (name) => ({ name }),
221572
+ configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221573
+ onChanged: () => deps.onChanged()
221574
+ });
221575
+ }
221576
+ /**
221577
+ * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221578
+ * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221579
+ */
221580
+ function reolinkInstancesProvider(instances, deps) {
221581
+ return {
221582
+ ...instances.toProvider(),
221583
+ instanceFormSchema: async ({ id }) => {
221584
+ if (id === null) return buildHubInstanceSchema();
221585
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221586
+ return evidence !== null && isHubIntegration({
221587
+ originStableId: evidence.originStableId,
221588
+ info: evidence.info,
221589
+ settings: body === null ? {} : hubSettingsOf(body)
221590
+ }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221591
+ }
221592
+ };
221593
+ }
221594
+ /**
221595
+ * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221596
+ * manual add by IP). An integration the registry cannot name is not a hub for this question.
221597
+ */
221598
+ async function integrationIsHub(instances, deps, id) {
221599
+ const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221600
+ if (evidence === null) return false;
221601
+ return isHubIntegration({
221602
+ originStableId: evidence.originStableId,
221603
+ info: evidence.info,
221604
+ settings: body === null ? {} : hubSettingsOf(body)
221605
+ });
221606
+ }
221607
+ //#endregion
221608
+ //#region src/mailbox-link-store.ts
221609
+ var INTEGRATIONS_MAX = 1e3;
221610
+ function mailboxLinkStoreOver(records) {
221611
+ const handle = records.kind(reolinkConnectionsEntryKind);
221612
+ return {
221613
+ list: async () => {
221614
+ return (await handle.query({ limit: INTEGRATIONS_MAX })).records.map((row) => {
221615
+ const linked = row.data[MAILBOX_LINK_FIELD];
221616
+ return {
221617
+ id: row.id,
221618
+ mailboxId: typeof linked === "string" ? linked : ""
221619
+ };
221620
+ });
221621
+ },
221622
+ set: async (integrationId, mailboxId) => {
221623
+ await handle.patch(integrationId, { [MAILBOX_LINK_FIELD]: mailboxId === "" ? null : mailboxId });
221624
+ }
221625
+ };
221626
+ }
221187
221627
  //#endregion
221188
221628
  //#region src/email-push-removal-hook.ts
221189
221629
  /**
@@ -221610,105 +222050,6 @@ async function moveEmailPushToMailbox(ports) {
221610
222050
  summary: { moved: true }
221611
222051
  };
221612
222052
  }
221613
- var reolinkConnectionsEntryKind = defineEntryKind("connections", {
221614
- title: "Reolink integrations",
221615
- schema: entryBody({
221616
- host: string().nullish(),
221617
- port: number().int().min(1).max(65535).nullish(),
221618
- rtspPort: number().int().min(1).max(65535).nullish(),
221619
- username: string().nullish(),
221620
- password: string().optional().meta({ secret: true }),
221621
- transport: _enum(["tcp", "udp"]).nullish(),
221622
- uid: string().nullish(),
221623
- debugGeneral: boolean().nullish(),
221624
- debugSocketLogs: array(ReolinkSocketDebugFlagSchema).nullish()
221625
- }),
221626
- writeTrigger: "an operator adds, edits or removes a Reolink integration, or a Hub device is migrated into one"
221627
- });
221628
- /** Every kind this addon declares, keyed by its name. */
221629
- var reolinkRecordKinds = { connections: reolinkConnectionsEntryKind };
221630
- /** The record body as the connection form's flat values: no name, no unset keys. */
221631
- function hubSettingsOf(body) {
221632
- const out = {};
221633
- for (const [key, value] of Object.entries(body)) {
221634
- if (key === "name" || value === null || value === void 0) continue;
221635
- out[key] = value;
221636
- }
221637
- return out;
221638
- }
221639
- /**
221640
- * What a resolved record says about its hub. A keychain that is locked yields a record WITHOUT
221641
- * its password: that is `password-locked`, never an empty password (D49).
221642
- */
221643
- function hubConnectionOf(resolved) {
221644
- const read = readHubConnection(hubSettingsOf(resolved.body));
221645
- return read.kind === "no-password" && resolved.secrets === "unavailable" ? { kind: "password-locked" } : read;
221646
- }
221647
- /**
221648
- * What each enabled integration's RECORD says about its hub: the one reader of the connection.
221649
- * A record that is absent reads as `no-host` (no session), exactly as an empty settings blob did.
221650
- */
221651
- async function readHubConnections(instances, integrations) {
221652
- const out = [];
221653
- for (const integration of integrations) {
221654
- const resolved = await instances.readResolved(integration.id);
221655
- out.push({
221656
- id: integration.id,
221657
- name: integration.name,
221658
- read: resolved === null ? { kind: "no-host" } : hubConnectionOf(resolved)
221659
- });
221660
- }
221661
- return out;
221662
- }
221663
- function buildReolinkInstances(records, deps) {
221664
- return new RecordIntegrationInstances(records, reolinkConnectionsEntryKind, {
221665
- description: {
221666
- role: "devices",
221667
- discovery: {
221668
- mode: "lan",
221669
- scopedToInstance: false
221670
- },
221671
- instanceMode: "multiple",
221672
- kind: "connection",
221673
- canTest: false
221674
- },
221675
- formSchema: () => buildHubInstanceSchema(),
221676
- initialBody: (name) => ({ name }),
221677
- configured: (body) => (body.host ?? "").length === 0 || (body.password ?? "").length > 0,
221678
- onChanged: () => deps.onChanged()
221679
- });
221680
- }
221681
- /**
221682
- * The provider handed to the hub: the default integration (no connection) shows no hub form, an
221683
- * NVR / Home Hub one does, and a create wizard (no id yet) sets up a hub.
221684
- */
221685
- function reolinkInstancesProvider(instances, deps) {
221686
- return {
221687
- ...instances.toProvider(),
221688
- instanceFormSchema: async ({ id }) => {
221689
- if (id === null) return buildHubInstanceSchema();
221690
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221691
- return evidence !== null && isHubIntegration({
221692
- originStableId: evidence.originStableId,
221693
- info: evidence.info,
221694
- settings: body === null ? {} : hubSettingsOf(body)
221695
- }) || body === null ? buildHubInstanceSchema() : { sections: [] };
221696
- }
221697
- };
221698
- }
221699
- /**
221700
- * Whether an integration IS one NVR / Home Hub (its devices come from the hub, so there is no
221701
- * manual add by IP). An integration the registry cannot name is not a hub for this question.
221702
- */
221703
- async function integrationIsHub(instances, deps, id) {
221704
- const [evidence, body] = await Promise.all([deps.registryEvidenceOf(id), instances.getResolved(id)]);
221705
- if (evidence === null) return false;
221706
- return isHubIntegration({
221707
- originStableId: evidence.originStableId,
221708
- info: evidence.info,
221709
- settings: body === null ? {} : hubSettingsOf(body)
221710
- });
221711
- }
221712
222053
  //#endregion
221713
222054
  //#region src/migrations/integration-rows-to-record.ts
221714
222055
  /**
@@ -222585,10 +222926,16 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222585
222926
  await this.mailboxPendingState.set(null);
222586
222927
  await this.mailboxPendingPasswordState.set("");
222587
222928
  }
222929
+ requireRecords() {
222930
+ const records = this.ctx.records;
222931
+ if (records === void 0) throw new Error("provider-reolink: ctx.records is required (hub-only addon)");
222932
+ return records;
222933
+ }
222588
222934
  /** The camera mailbox bridge, built once. */
222589
222935
  ensureEmailBridge() {
222590
222936
  this.emailBridge ??= new EmailPushBridge({
222591
222937
  port: createBrokerPort(this.ctx.api),
222938
+ links: mailboxLinkStoreOver(this.requireRecords()),
222592
222939
  listCameras: () => this.listReolinkCameras(),
222593
222940
  logger: this.ctx.logger.child("email-push"),
222594
222941
  pending: {
@@ -222754,8 +223101,9 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222754
223101
  if (typeof addonId === "string" && addonId !== this.ctx.id) return;
222755
223102
  this.reconcileIntegrations();
222756
223103
  };
222757
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, handler);
222758
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, handler);
223104
+ this.instances?.onSwitched(() => {
223105
+ this.reconcileIntegrations();
223106
+ });
222759
223107
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, handler);
222760
223108
  }
222761
223109
  /** The hub box follows its integration's socket. */
@@ -222999,6 +223347,10 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
222999
223347
  });
223000
223348
  this.instances = instances;
223001
223349
  this.hubIntegrationProbe = (id) => integrationIsHub(instances, { registryEvidenceOf }, id);
223350
+ this.declareRegistrySwitch({
223351
+ kind: reolinkConnectionsEntryKind,
223352
+ initialBody: (name) => ({ name })
223353
+ });
223002
223354
  await this.runMigrations([...defineAddonMigrations(REOLINK_MIGRATIONS, this.migrationPorts()), ...defineAddonMigrations(REOLINK_INTEGRATION_MIGRATIONS, integrationPorts)]);
223003
223355
  this.wireEmailBridge();
223004
223356
  const wireSleepPushResolvers = (event, via) => {