@camstack/addon-provider-enpal 0.1.11 → 0.1.12

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
@@ -5981,7 +5981,7 @@ var ZodIssueCode = {
5981
5981
  var ZodFirstPartyTypeKind;
5982
5982
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5983
5983
  //#endregion
5984
- //#region ../types/dist/sleep-BX_MqzUe.mjs
5984
+ //#region ../types/dist/sleep-CmjWurK5.mjs
5985
5985
  /**
5986
5986
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5987
5987
  * window to float samples (D455).
@@ -6665,137 +6665,153 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6665
6665
  blockOwner
6666
6666
  };
6667
6667
  }
6668
- /**
6669
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6670
- * `read`/`write` are the addon-store or device-store accessors. The whole
6671
- * validated value round-trips on every read/write — the schema is the
6672
- * single source of truth for what is persisted, so no hand-listed field
6673
- * set can drop a key on save.
6674
- */
6675
- function createDurableState(deps) {
6676
- const get = async () => {
6677
- const raw = (await deps.read())[deps.key];
6678
- if (raw === void 0) return deps.fallback;
6679
- const parsed = deps.schema.safeParse(raw);
6680
- if (!parsed.success) {
6681
- deps.onParseError?.(deps.key, parsed.error);
6682
- return deps.fallback;
6683
- }
6684
- return parsed.data;
6685
- };
6686
- const set = async (next) => {
6687
- const validated = deps.schema.parse(next);
6688
- await deps.write({ [deps.key]: validated });
6689
- };
6690
- const update = async (fn) => {
6691
- await set(fn(await get()));
6692
- };
6668
+ function secretsOverMigrationApi(api) {
6693
6669
  return {
6694
- get,
6695
- set,
6696
- update
6670
+ resolve: async (refs) => {
6671
+ const { values } = await api.secrets.resolve({ refs: [...refs] });
6672
+ const out = {};
6673
+ for (const ref of refs) {
6674
+ const value = values[ref];
6675
+ out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
6676
+ kind: "value",
6677
+ value,
6678
+ version: 0
6679
+ };
6680
+ }
6681
+ return out;
6682
+ },
6683
+ delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
6697
6684
  };
6698
6685
  }
6699
- /**
6700
- * Per-node scoping for the shared addon-settings blob.
6701
- *
6702
- * An addon's settings store is hub-central (the `addon-settings` cap is
6703
- * hub-routed — the hub instance answers for every node), so fields whose
6704
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6705
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6706
- * the single shared blob. The SCHEMA field key stays bare: the write path
6707
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6708
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6709
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6710
- *
6711
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6712
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6713
- * schema and routes reads/writes through these helpers.
6714
- *
6715
- * ## No bare-key fallback — deliberate
6716
- *
6717
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6718
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6719
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6720
- * the store is invisible to every node, hub included, so one node's
6721
- * selection can never leak onto another. (This generalizes the
6722
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6723
- * arbitrary set of per-node field keys.)
6724
- *
6725
- * Pure functions only — no I/O, no imports beyond the language. This is a
6726
- * LEAF module: import it via its deep path, never from the root barrel.
6727
- */
6728
- /**
6729
- * Normalize a raw kernel node id to the bare node id used for scoping.
6730
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6731
- * processes; per-node settings are per-NODE, so strip the addon segment.
6732
- * `undefined` / `null` / empty falls back to `'hub'`.
6733
- */
6734
- function normalizeNodeId(raw) {
6735
- if (raw === void 0 || raw === null || raw === "") return "hub";
6736
- const slashIdx = raw.indexOf("/");
6737
- if (slashIdx < 0) return raw;
6738
- const bare = raw.slice(0, slashIdx);
6739
- return bare === "" ? "hub" : bare;
6686
+ /** The record calls the one-switch migration makes, over the migration API. */
6687
+ function switchRecordsOverMigrationApi(api) {
6688
+ return { kind: (definition) => {
6689
+ const handle = api.records.kind(definition);
6690
+ return {
6691
+ get: (id) => handle.get({ id }),
6692
+ put: (input, opts) => handle.put({
6693
+ ...input,
6694
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6695
+ }),
6696
+ patch: (id, partial) => handle.patch({
6697
+ id,
6698
+ partial
6699
+ })
6700
+ };
6701
+ } };
6740
6702
  }
6741
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6742
- function nodeScopedKey(base, nodeId) {
6743
- return `${base}@${normalizeNodeId(nodeId)}`;
6703
+ /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
6704
+ function recordsOverMigrationApi(api) {
6705
+ return { kind: (definition) => {
6706
+ const handle = api.records.kind(definition);
6707
+ return {
6708
+ get: (id) => handle.get({ id }),
6709
+ getResolved: (id) => handle.getResolved({ id }),
6710
+ put: (input, opts) => handle.put({
6711
+ ...input,
6712
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6713
+ }),
6714
+ delete: (id) => handle.delete({ id })
6715
+ };
6716
+ } };
6744
6717
  }
6745
- /**
6746
- * Read a node's value for a per-node field from the raw shared store:
6747
- * the node-scoped key when present, otherwise `undefined`.
6748
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6749
- * schema `default` win on `undefined`.
6750
- */
6751
- function readNodeValue(store, base, nodeId) {
6752
- return store[nodeScopedKey(base, nodeId)];
6718
+ function integrationRowsApiOver(api) {
6719
+ return {
6720
+ list: async () => (await api.integrations.list({})).integrations,
6721
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6722
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6723
+ };
6753
6724
  }
6754
6725
  /**
6755
- * Re-map a UI/settings patch so every bare perNode field persists under the
6756
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6757
- * the write path so a save for one node never clobbers another node's value
6758
- * (and the bare key is never written). Returns a new object — the input
6759
- * patch is not mutated.
6726
+ * One serial lane per migration API: a log line is delivered after the line before it, so the
6727
+ * order the steps wrote them in is the order the hub reads them in. A delivery that fails
6728
+ * is reported once through the same door; if that fails too nothing is left to tell, and the
6729
+ * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
6760
6730
  */
6761
- function scopePatch(patch, perNodeKeys, nodeId) {
6762
- const out = {};
6763
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6764
- return out;
6731
+ var lanes = /* @__PURE__ */ new WeakMap();
6732
+ function deliver(api, send) {
6733
+ const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
6734
+ const reason = error instanceof Error ? error.message : String(error);
6735
+ await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
6736
+ });
6737
+ lanes.set(api, next);
6738
+ return next;
6765
6739
  }
6766
- /**
6767
- * Project the raw shared store onto the bare schema keys for ONE node so a
6768
- * UI schema (whose field keys are bare) hydrates from that node's own
6769
- * values:
6770
- *
6771
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6772
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6773
- * legacy key must never hydrate any node — no bare fallback).
6774
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6775
- * each bare perNode key; when the node has no scoped key the bare key is
6776
- * left ABSENT so the field's schema `default` wins.
6777
- *
6778
- * Returns a new object — the input store is not mutated.
6779
- */
6780
- function projectStore(store, perNodeKeys, nodeId) {
6781
- const out = {};
6782
- for (const [key, value] of Object.entries(store)) {
6783
- if (key.includes("@")) continue;
6784
- if (perNodeKeys.has(key)) continue;
6785
- out[key] = value;
6740
+ function warnOver(api) {
6741
+ return (message) => deliver(api, () => api.log.warn({ message }));
6742
+ }
6743
+ /** What the rows-to-records move needs, over the migration API. */
6744
+ function rowsDepsOver(api) {
6745
+ return {
6746
+ api: integrationRowsApiOver(api),
6747
+ records: recordsOverMigrationApi(api),
6748
+ secrets: secretsOverMigrationApi(api),
6749
+ warn: warnOver(api)
6750
+ };
6751
+ }
6752
+ var PREFIX = "records/";
6753
+ /** The base of every records failure. `detail` is the human part of the message. */
6754
+ var RecordsError = class extends Error {
6755
+ code;
6756
+ detail;
6757
+ constructor(code, detail) {
6758
+ super(`${PREFIX}${code}: ${detail}`);
6759
+ this.name = "RecordsError";
6760
+ this.code = code;
6761
+ this.detail = detail;
6786
6762
  }
6787
- for (const base of perNodeKeys) {
6788
- const value = readNodeValue(store, base, nodeId);
6789
- if (value !== void 0) out[base] = value;
6763
+ };
6764
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6765
+ var RevConflictError = class extends RecordsError {
6766
+ constructor(detail) {
6767
+ super("rev-conflict", detail);
6768
+ this.name = "RevConflictError";
6790
6769
  }
6791
- return out;
6770
+ };
6771
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6772
+ var RecordSecretUnavailableError = class extends RecordsError {
6773
+ constructor(detail) {
6774
+ super("secret-unavailable", detail);
6775
+ this.name = "RecordSecretUnavailableError";
6776
+ }
6777
+ };
6778
+ var InvalidRecordError = class extends RecordsError {
6779
+ constructor(detail) {
6780
+ super("invalid-record", detail);
6781
+ this.name = "InvalidRecordError";
6782
+ }
6783
+ };
6784
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6785
+ var DeclarationRefusedError = class extends RecordsError {
6786
+ constructor(detail) {
6787
+ super("declaration-refused", detail);
6788
+ this.name = "DeclarationRefusedError";
6789
+ }
6790
+ };
6791
+ function linkTargetOf(meta) {
6792
+ if (typeof meta !== "object" || meta === null) return void 0;
6793
+ const link = Reflect.get(meta, "link");
6794
+ const parsed = LinkTargetSchema.safeParse(link);
6795
+ return parsed.success ? parsed.data : void 0;
6796
+ }
6797
+ var LinkTargetSchema = object({
6798
+ cap: string().min(1),
6799
+ kind: string().min(1).optional()
6800
+ });
6801
+ /** The links a kind declares, read from the meta of its body fields. */
6802
+ function linksOfKind(kind) {
6803
+ const schema = kind.schema;
6804
+ if (!(schema instanceof ZodObject)) return [];
6805
+ const links = [];
6806
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6807
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6808
+ if (to !== void 0) links.push({
6809
+ field,
6810
+ to
6811
+ });
6812
+ }
6813
+ return links;
6792
6814
  }
6793
- /** Every scope, in the order the guard and the docs list them. */
6794
- var SCOPED_SETTINGS_SCOPES = [
6795
- "cluster",
6796
- "device-defaults",
6797
- "node"
6798
- ];
6799
6815
  /**
6800
6816
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6801
6817
  *
@@ -6930,6 +6946,652 @@ function parseSecretRef(ref) {
6930
6946
  fieldPath
6931
6947
  };
6932
6948
  }
6949
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6950
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6951
+ var RECORD_DATABASES = ["settings", "events"];
6952
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6953
+ var RECORD_CLASSES = [
6954
+ "config",
6955
+ "ledger",
6956
+ "audit",
6957
+ "mirror",
6958
+ "ephemeral"
6959
+ ];
6960
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6961
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6962
+ var RECORD_BATCH_MAX = 1e3;
6963
+ var RECORD_QUERY_MAX = 1e3;
6964
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6965
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6966
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6967
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6968
+ /**
6969
+ * Secret fields of a record, addressed the way a Zod schema declares them
6970
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6971
+ * (`auth.accessToken`, `headers[].value`).
6972
+ *
6973
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6974
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6975
+ * key releases exactly that key's secret.
6976
+ *
6977
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6978
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6979
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6980
+ * leaf names its element: `headers[X-Api].value`.
6981
+ *
6982
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6983
+ */
6984
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6985
+ function parseSecretPath(path) {
6986
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6987
+ return path.split(".").map((raw) => {
6988
+ const each = raw.endsWith("[]");
6989
+ const map = raw.endsWith("{}");
6990
+ const key = each || map ? raw.slice(0, -2) : raw;
6991
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6992
+ return {
6993
+ key,
6994
+ each,
6995
+ map
6996
+ };
6997
+ });
6998
+ }
6999
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
7000
+ function secretArrayPrefixes(path) {
7001
+ const segments = parseSecretPath(path);
7002
+ const prefixes = [];
7003
+ const walked = [];
7004
+ for (const segment of segments) {
7005
+ walked.push(segment.key);
7006
+ if (segment.each) prefixes.push(walked.join("."));
7007
+ }
7008
+ return prefixes;
7009
+ }
7010
+ function isRecord$6(value) {
7011
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7012
+ }
7013
+ function elementId(element, idKey, declared, prefix) {
7014
+ const id = isRecord$6(element) ? element[idKey] : void 0;
7015
+ 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`);
7016
+ return id;
7017
+ }
7018
+ /**
7019
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
7020
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7021
+ * result is a new body, `data` is untouched.
7022
+ */
7023
+ var REMOVE_LEAF = Symbol("remove-leaf");
7024
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7025
+ if (!isRecord$6(node)) return node;
7026
+ const segment = segments[index];
7027
+ if (segment === void 0) return node;
7028
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7029
+ const child = node[segment.key];
7030
+ const keys = [...walkedKeys, segment.key];
7031
+ const last = index === segments.length - 1;
7032
+ if (segment.each) {
7033
+ if (!Array.isArray(child)) return node;
7034
+ const prefix = keys.join(".");
7035
+ const idKey = arrayKeys[prefix];
7036
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7037
+ const mapped = child.map((element) => {
7038
+ const id = elementId(element, idKey, declared, prefix);
7039
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7040
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7041
+ });
7042
+ return {
7043
+ ...node,
7044
+ [segment.key]: mapped
7045
+ };
7046
+ }
7047
+ if (segment.map) {
7048
+ if (!isRecord$6(child)) return node;
7049
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7050
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7051
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7052
+ return [mapKey, visit({
7053
+ declared,
7054
+ concrete,
7055
+ value
7056
+ })];
7057
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7058
+ return {
7059
+ ...node,
7060
+ [segment.key]: Object.fromEntries(kept)
7061
+ };
7062
+ }
7063
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7064
+ if (last) {
7065
+ const replacement = visit({
7066
+ declared,
7067
+ concrete,
7068
+ value: child
7069
+ });
7070
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7071
+ return {
7072
+ ...node,
7073
+ [segment.key]: replacement
7074
+ };
7075
+ }
7076
+ return {
7077
+ ...node,
7078
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7079
+ };
7080
+ }
7081
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7082
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7083
+ let current = data;
7084
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7085
+ return current;
7086
+ }
7087
+ /** Every present secret leaf, read-only. */
7088
+ function collectSecretLeaves(data, paths, arrayKeys) {
7089
+ const found = [];
7090
+ mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
7091
+ found.push(leaf);
7092
+ return leaf.value;
7093
+ });
7094
+ return found;
7095
+ }
7096
+ /**
7097
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7098
+ * record's refs never collide with the refs a legacy collection of the same name
7099
+ * already holds during an adoption.
7100
+ */
7101
+ function recordSecretCollection(kind) {
7102
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7103
+ }
7104
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7105
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7106
+ return buildSecretRef({
7107
+ owner,
7108
+ scope: {
7109
+ kind: "row",
7110
+ collection: recordSecretCollection(kind),
7111
+ rowId
7112
+ },
7113
+ fieldPath: concretePath
7114
+ });
7115
+ }
7116
+ /**
7117
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7118
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7119
+ * token. The form hands it to the secret field, which reveals the value by ref
7120
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7121
+ * stored secret (the records door reads a view as KEEP).
7122
+ *
7123
+ * ONE implementation for the entries service and for every addon that serves
7124
+ * its own instances (`RecordIntegrationInstances`).
7125
+ */
7126
+ function isRecord$5(value) {
7127
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7128
+ }
7129
+ function secretViewsOf(owner, kind, id, decl, data) {
7130
+ if (decl.secretPaths.length === 0) return data;
7131
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7132
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7133
+ return {
7134
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7135
+ v: 1,
7136
+ set: true
7137
+ };
7138
+ });
7139
+ return isRecord$5(shown) ? shown : data;
7140
+ }
7141
+ /** The most instances one addon lists (an integrations page, not a table). */
7142
+ var INSTANCES_LIST_MAX = 1e3;
7143
+ /**
7144
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7145
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7146
+ */
7147
+ function isInstanceEnabled(body) {
7148
+ return body.enabled !== false;
7149
+ }
7150
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7151
+ var SWITCH_KEY = "enabled";
7152
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7153
+ function topLevelSecretKeys(paths) {
7154
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7155
+ }
7156
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7157
+ function secretMapKeys(paths) {
7158
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7159
+ }
7160
+ /**
7161
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7162
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7163
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7164
+ */
7165
+ function secretMapPatch(value) {
7166
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7167
+ const out = {};
7168
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7169
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7170
+ return Object.keys(out).length > 0 ? out : null;
7171
+ }
7172
+ var RecordIntegrationInstances = class {
7173
+ records;
7174
+ kind;
7175
+ hooks;
7176
+ handle;
7177
+ secretKeys;
7178
+ secretMaps;
7179
+ nameField;
7180
+ switchListeners = /* @__PURE__ */ new Set();
7181
+ constructor(records, kind, hooks) {
7182
+ this.records = records;
7183
+ this.kind = kind;
7184
+ this.hooks = hooks;
7185
+ this.handle = records.kind(kind);
7186
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7187
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7188
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7189
+ }
7190
+ /**
7191
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7192
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7193
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7194
+ */
7195
+ async readResolved(id) {
7196
+ try {
7197
+ const record = await this.handle.getResolved(id);
7198
+ return record === null ? null : {
7199
+ id,
7200
+ body: record.data,
7201
+ enabled: isInstanceEnabled(record.data),
7202
+ secrets: "resolved"
7203
+ };
7204
+ } catch (err) {
7205
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7206
+ const stored = await this.handle.get(id);
7207
+ if (stored === null) return null;
7208
+ return {
7209
+ id,
7210
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7211
+ enabled: isInstanceEnabled(stored.data),
7212
+ secrets: "unavailable"
7213
+ };
7214
+ }
7215
+ }
7216
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7217
+ async getResolved(id) {
7218
+ return (await this.readResolved(id))?.body ?? null;
7219
+ }
7220
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7221
+ async listResolved() {
7222
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7223
+ const out = [];
7224
+ for (const record of page.records) {
7225
+ const read = await this.readResolved(record.id);
7226
+ if (read !== null) out.push(read);
7227
+ }
7228
+ return out;
7229
+ }
7230
+ viewOf(record) {
7231
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7232
+ const rawName = record.data[this.nameField];
7233
+ const kind = this.hooks.kindOf?.(record.data);
7234
+ const health = this.hooks.health?.(record.data, record.id);
7235
+ return {
7236
+ id: record.id,
7237
+ name: typeof rawName === "string" ? rawName : record.id,
7238
+ configured: this.hooks.configured(record.data),
7239
+ enabled: isInstanceEnabled(record.data),
7240
+ formValues: shown,
7241
+ ...kind !== void 0 ? { kind } : {},
7242
+ ...health?.status !== void 0 ? { status: health.status } : {},
7243
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7244
+ };
7245
+ }
7246
+ describe = async () => {
7247
+ const declared = linksOfKind(this.kind);
7248
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7249
+ kind: this.kind.name,
7250
+ field: link.field,
7251
+ to: link.to
7252
+ })) };
7253
+ return {
7254
+ ...this.hooks.description,
7255
+ ...links,
7256
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7257
+ };
7258
+ };
7259
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7260
+ listInstances = async () => {
7261
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7262
+ };
7263
+ getInstance = async ({ id }) => {
7264
+ const record = await this.handle.get(id);
7265
+ return record === null ? null : this.viewOf(record);
7266
+ };
7267
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7268
+ createInstance = async ({ id, name, kind, values }) => {
7269
+ const minted = id ?? this.hooks.mintId?.({
7270
+ name,
7271
+ ...kind !== void 0 ? { kind } : {}
7272
+ });
7273
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7274
+ await this.handle.put({
7275
+ id: minted,
7276
+ data: this.hooks.initialBody(name, kind)
7277
+ }, { ifRev: 0 });
7278
+ const patch = this.patchOf(values ?? {});
7279
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7280
+ await this.hooks.onChanged?.(minted, "created");
7281
+ return { id: minted };
7282
+ };
7283
+ updateInstance = async ({ id, name, values }) => {
7284
+ const patch = this.patchOf(values);
7285
+ if (name !== void 0) patch[this.nameField] = name;
7286
+ await this.handle.patch(id, patch);
7287
+ await this.hooks.onChanged?.(id, "updated");
7288
+ return { ok: true };
7289
+ };
7290
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7291
+ patchOf(values) {
7292
+ const patch = {};
7293
+ for (const [key, value] of Object.entries(values)) {
7294
+ if (value === void 0) continue;
7295
+ if (key === "enabled") continue;
7296
+ if (this.secretMaps.has(key)) {
7297
+ const entries = secretMapPatch(value);
7298
+ if (entries !== null) patch[key] = entries;
7299
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7300
+ else if (isSecretClear(value)) patch[key] = null;
7301
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7302
+ }
7303
+ return patch;
7304
+ }
7305
+ /**
7306
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7307
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7308
+ * addon reconciles from the record, whichever way it flipped.
7309
+ */
7310
+ onSwitched(listener) {
7311
+ this.switchListeners.add(listener);
7312
+ }
7313
+ /**
7314
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7315
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7316
+ * never configured) gets its record from `initialBody` before the switch is written.
7317
+ */
7318
+ setInstanceEnabled = async ({ id, enabled }) => {
7319
+ if (await this.handle.get(id) === null) await this.handle.put({
7320
+ id,
7321
+ data: this.hooks.initialBody(id)
7322
+ }, { ifRev: 0 });
7323
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7324
+ await this.hooks.onChanged?.(id, "enabled");
7325
+ for (const listener of this.switchListeners) await listener(id, enabled);
7326
+ return { ok: true };
7327
+ };
7328
+ /** The row and its keychain refs go together (the records door). */
7329
+ deleteInstance = async ({ id }) => {
7330
+ await this.handle.delete(id);
7331
+ await this.hooks.onChanged?.(id, "deleted");
7332
+ return { ok: true };
7333
+ };
7334
+ testInstance = async (input) => {
7335
+ if (this.hooks.test === void 0) return {
7336
+ success: false,
7337
+ status: "unsupported",
7338
+ error: "This integration declares no connection test"
7339
+ };
7340
+ return this.hooks.test(input);
7341
+ };
7342
+ /** The flat provider object to hand to `registerProvider`. */
7343
+ toProvider() {
7344
+ return {
7345
+ describe: this.describe,
7346
+ instanceFormSchema: this.instanceFormSchema,
7347
+ listInstances: this.listInstances,
7348
+ getInstance: this.getInstance,
7349
+ createInstance: this.createInstance,
7350
+ updateInstance: this.updateInstance,
7351
+ setInstanceEnabled: this.setInstanceEnabled,
7352
+ deleteInstance: this.deleteInstance,
7353
+ testInstance: this.testInstance
7354
+ };
7355
+ }
7356
+ };
7357
+ /**
7358
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7359
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7360
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7361
+ *
7362
+ * For every registry row of the addon that is OFF:
7363
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7364
+ * (a default integration that never had settings, Reolink's among them);
7365
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7366
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7367
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7368
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7369
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7370
+ *
7371
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7372
+ * which is also why `integrations.list` still answers the stored column at that point.
7373
+ */
7374
+ function registrySwitchToBodyId(addonId, date) {
7375
+ return `${addonId}/${date}-registry-switch-to-body`;
7376
+ }
7377
+ async function moveRegistrySwitchToBody(ports, spec) {
7378
+ const rows = await ports.listIntegrations(spec.addonId);
7379
+ let created = 0;
7380
+ let switched = 0;
7381
+ let kept = 0;
7382
+ for (const row of rows) {
7383
+ if (row.enabled) continue;
7384
+ const body = await ports.readBody(row.id);
7385
+ if (body === null) {
7386
+ if (await ports.createRecord(row.id, {
7387
+ ...spec.initialBody(row.name),
7388
+ ["enabled"]: false
7389
+ }) === "created") created += 1;
7390
+ else kept += 1;
7391
+ continue;
7392
+ }
7393
+ if ("enabled" in body) {
7394
+ kept += 1;
7395
+ continue;
7396
+ }
7397
+ await ports.switchOff(row.id);
7398
+ switched += 1;
7399
+ }
7400
+ const summary = {
7401
+ integrations: rows.length,
7402
+ off: rows.filter((r) => !r.enabled).length,
7403
+ created,
7404
+ switched,
7405
+ kept
7406
+ };
7407
+ return created === 0 && switched === 0 ? {
7408
+ outcome: "already-done",
7409
+ summary
7410
+ } : {
7411
+ outcome: "done",
7412
+ summary
7413
+ };
7414
+ }
7415
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7416
+ function registrySwitchToBodyMigration(spec) {
7417
+ return {
7418
+ meta: {
7419
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7420
+ owner: spec.addonId,
7421
+ level: "addon-state",
7422
+ seq: spec.seq,
7423
+ dependsOn: [],
7424
+ store: "settings",
7425
+ scope: "cluster",
7426
+ onFailure: "block-owner",
7427
+ bodyKind: "procedure",
7428
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7429
+ fixtureMark: "enabled"
7430
+ },
7431
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7432
+ addonId: spec.addonId,
7433
+ initialBody: spec.initialBody
7434
+ })
7435
+ };
7436
+ }
7437
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7438
+ function registrySwitchPortsOver(deps) {
7439
+ const handle = deps.records.kind({
7440
+ name: deps.kind.name,
7441
+ declaration: deps.kind.declaration,
7442
+ schema: record(string(), unknown())
7443
+ });
7444
+ return {
7445
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7446
+ id: i.id,
7447
+ name: i.name,
7448
+ enabled: i.enabled !== false
7449
+ })),
7450
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7451
+ createRecord: async (id, body) => {
7452
+ if (await handle.get(id) !== null) return "exists";
7453
+ await handle.put({
7454
+ id,
7455
+ data: body
7456
+ }, { ifRev: 0 });
7457
+ return "created";
7458
+ },
7459
+ switchOff: async (id) => {
7460
+ await handle.patch(id, { [SWITCH_KEY]: false });
7461
+ }
7462
+ };
7463
+ }
7464
+ /**
7465
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7466
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7467
+ * validated value round-trips on every read/write — the schema is the
7468
+ * single source of truth for what is persisted, so no hand-listed field
7469
+ * set can drop a key on save.
7470
+ */
7471
+ function createDurableState(deps) {
7472
+ const get = async () => {
7473
+ const raw = (await deps.read())[deps.key];
7474
+ if (raw === void 0) return deps.fallback;
7475
+ const parsed = deps.schema.safeParse(raw);
7476
+ if (!parsed.success) {
7477
+ deps.onParseError?.(deps.key, parsed.error);
7478
+ return deps.fallback;
7479
+ }
7480
+ return parsed.data;
7481
+ };
7482
+ const set = async (next) => {
7483
+ const validated = deps.schema.parse(next);
7484
+ await deps.write({ [deps.key]: validated });
7485
+ };
7486
+ const update = async (fn) => {
7487
+ await set(fn(await get()));
7488
+ };
7489
+ return {
7490
+ get,
7491
+ set,
7492
+ update
7493
+ };
7494
+ }
7495
+ /**
7496
+ * Per-node scoping for the shared addon-settings blob.
7497
+ *
7498
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7499
+ * hub-routed — the hub instance answers for every node), so fields whose
7500
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7501
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7502
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7503
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7504
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7505
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7506
+ *
7507
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7508
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7509
+ * schema and routes reads/writes through these helpers.
7510
+ *
7511
+ * ## No bare-key fallback — deliberate
7512
+ *
7513
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7514
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7515
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7516
+ * the store is invisible to every node, hub included, so one node's
7517
+ * selection can never leak onto another. (This generalizes the
7518
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7519
+ * arbitrary set of per-node field keys.)
7520
+ *
7521
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7522
+ * LEAF module: import it via its deep path, never from the root barrel.
7523
+ */
7524
+ /**
7525
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7526
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7527
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7528
+ * `undefined` / `null` / empty falls back to `'hub'`.
7529
+ */
7530
+ function normalizeNodeId(raw) {
7531
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7532
+ const slashIdx = raw.indexOf("/");
7533
+ if (slashIdx < 0) return raw;
7534
+ const bare = raw.slice(0, slashIdx);
7535
+ return bare === "" ? "hub" : bare;
7536
+ }
7537
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7538
+ function nodeScopedKey(base, nodeId) {
7539
+ return `${base}@${normalizeNodeId(nodeId)}`;
7540
+ }
7541
+ /**
7542
+ * Read a node's value for a per-node field from the raw shared store:
7543
+ * the node-scoped key when present, otherwise `undefined`.
7544
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7545
+ * schema `default` win on `undefined`.
7546
+ */
7547
+ function readNodeValue(store, base, nodeId) {
7548
+ return store[nodeScopedKey(base, nodeId)];
7549
+ }
7550
+ /**
7551
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7552
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7553
+ * the write path so a save for one node never clobbers another node's value
7554
+ * (and the bare key is never written). Returns a new object — the input
7555
+ * patch is not mutated.
7556
+ */
7557
+ function scopePatch(patch, perNodeKeys, nodeId) {
7558
+ const out = {};
7559
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7560
+ return out;
7561
+ }
7562
+ /**
7563
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7564
+ * UI schema (whose field keys are bare) hydrates from that node's own
7565
+ * values:
7566
+ *
7567
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7568
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7569
+ * legacy key must never hydrate any node — no bare fallback).
7570
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7571
+ * each bare perNode key; when the node has no scoped key the bare key is
7572
+ * left ABSENT so the field's schema `default` wins.
7573
+ *
7574
+ * Returns a new object — the input store is not mutated.
7575
+ */
7576
+ function projectStore(store, perNodeKeys, nodeId) {
7577
+ const out = {};
7578
+ for (const [key, value] of Object.entries(store)) {
7579
+ if (key.includes("@")) continue;
7580
+ if (perNodeKeys.has(key)) continue;
7581
+ out[key] = value;
7582
+ }
7583
+ for (const base of perNodeKeys) {
7584
+ const value = readNodeValue(store, base, nodeId);
7585
+ if (value !== void 0) out[base] = value;
7586
+ }
7587
+ return out;
7588
+ }
7589
+ /** Every scope, in the order the guard and the docs list them. */
7590
+ var SCOPED_SETTINGS_SCOPES = [
7591
+ "cluster",
7592
+ "device-defaults",
7593
+ "node"
7594
+ ];
6933
7595
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6934
7596
  var KeychainWriteRefusedError = class extends Error {
6935
7597
  fieldPath;
@@ -6940,7 +7602,7 @@ var KeychainWriteRefusedError = class extends Error {
6940
7602
  }
6941
7603
  };
6942
7604
  var KEEP = { kind: "keep" };
6943
- function isRecord$6(value) {
7605
+ function isRecord$4(value) {
6944
7606
  return typeof value === "object" && value !== null && !Array.isArray(value);
6945
7607
  }
6946
7608
  function defaultMintId() {
@@ -6953,7 +7615,7 @@ function collectSecretMarkerRefs(value, out = []) {
6953
7615
  return out;
6954
7616
  }
6955
7617
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6956
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7618
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6957
7619
  return out;
6958
7620
  }
6959
7621
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7008,7 +7670,7 @@ function rowId(row, idKey) {
7008
7670
  return null;
7009
7671
  }
7010
7672
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7011
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7673
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7012
7674
  if (!Array.isArray(incoming)) {
7013
7675
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7014
7676
  return {
@@ -7024,7 +7686,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7024
7686
  const kept = /* @__PURE__ */ new Set();
7025
7687
  const rows = [];
7026
7688
  for (const row of incoming) {
7027
- if (!isRecord$6(row)) {
7689
+ if (!isRecord$4(row)) {
7028
7690
  rows.push(row);
7029
7691
  continue;
7030
7692
  }
@@ -7049,7 +7711,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7049
7711
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7050
7712
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7051
7713
  case "object": {
7052
- if (!isRecord$6(incoming)) {
7714
+ if (!isRecord$4(incoming)) {
7053
7715
  if (incoming === void 0) return KEEP;
7054
7716
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7055
7717
  return {
@@ -7057,7 +7719,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7057
7719
  value: incoming
7058
7720
  };
7059
7721
  }
7060
- const storedObj = isRecord$6(stored) ? stored : {};
7722
+ const storedObj = isRecord$4(stored) ? stored : {};
7061
7723
  return {
7062
7724
  kind: "value",
7063
7725
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7180,7 +7842,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7180
7842
  value: items
7181
7843
  };
7182
7844
  }
7183
- if (isRecord$6(v)) {
7845
+ if (isRecord$4(v)) {
7184
7846
  const out = {};
7185
7847
  for (const [k, child] of Object.entries(v)) {
7186
7848
  const s = substitute(child);
@@ -7212,7 +7874,7 @@ var SecretOverwriteRefusedError = class extends Error {
7212
7874
  this.name = "SecretOverwriteRefusedError";
7213
7875
  }
7214
7876
  };
7215
- function isRecord$5(value) {
7877
+ function isRecord$3(value) {
7216
7878
  return typeof value === "object" && value !== null && !Array.isArray(value);
7217
7879
  }
7218
7880
  function resolvedValue(pass, marker) {
@@ -7241,7 +7903,7 @@ function inArray(pass, incoming, stored) {
7241
7903
  return incoming.map((item, index) => {
7242
7904
  const twin = stored[index];
7243
7905
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7244
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7906
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7245
7907
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7246
7908
  return item;
7247
7909
  });
@@ -7252,7 +7914,7 @@ function inArrayRow(pass, incoming, stored) {
7252
7914
  const twin = stored[key];
7253
7915
  if (isSecretMarker(twin)) {
7254
7916
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7255
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7917
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7256
7918
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7257
7919
  }
7258
7920
  return out;
@@ -7260,7 +7922,7 @@ function inArrayRow(pass, incoming, stored) {
7260
7922
  async function walk(pass, incoming, stored) {
7261
7923
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7262
7924
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7263
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7925
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7264
7926
  const out = { ...incoming };
7265
7927
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7266
7928
  return out;
@@ -7291,7 +7953,7 @@ async function restoreUnchangedSecrets(input) {
7291
7953
  function isJsonEqual(a, b) {
7292
7954
  if (Object.is(a, b)) return true;
7293
7955
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7294
- if (isRecord$5(a) && isRecord$5(b)) {
7956
+ if (isRecord$3(a) && isRecord$3(b)) {
7295
7957
  const keys = Object.keys(a);
7296
7958
  if (keys.length !== Object.keys(b).length) return false;
7297
7959
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7315,7 +7977,7 @@ function markerKeysOf(blob, owner) {
7315
7977
  }
7316
7978
  function nodeFromStored(value, owner) {
7317
7979
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7318
- if (!isRecord$5(value)) return null;
7980
+ if (!isRecord$3(value)) return null;
7319
7981
  const children = /* @__PURE__ */ new Map();
7320
7982
  for (const [key, child] of Object.entries(value)) {
7321
7983
  const node = nodeFromStored(child, owner);
@@ -7812,13 +8474,48 @@ var BaseAddon = class {
7812
8474
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7813
8475
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7814
8476
  }
7815
- async runBound(migrations, options) {
8477
+ /**
8478
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8479
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8480
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8481
+ * on every declare).
8482
+ */
8483
+ declareRegistrySwitch(spec) {
8484
+ this.registrySwitchSpec = spec;
8485
+ }
8486
+ registrySwitchSpec = null;
8487
+ registrySwitchBound() {
8488
+ const spec = this.registrySwitchSpec;
8489
+ if (spec === null) return [];
8490
+ const api = this.ctx.migrationApi;
8491
+ if (api === void 0) {
8492
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8493
+ return [];
8494
+ }
8495
+ return migrationSet([registrySwitchToBodyMigration({
8496
+ addonId: this.ctx.id,
8497
+ date: "2026-11-06",
8498
+ seq: 1e3,
8499
+ initialBody: spec.initialBody
8500
+ })], (a) => registrySwitchPortsOver({
8501
+ api: integrationRowsApiOver(a),
8502
+ records: switchRecordsOverMigrationApi(a),
8503
+ kind: spec.kind
8504
+ })).bind(api);
8505
+ }
8506
+ async runBound(declared, options) {
8507
+ const added = this.registrySwitchBound();
8508
+ const migrations = [...declared, ...added];
8509
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8510
+ ...options,
8511
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8512
+ };
7816
8513
  const api = this.ctx.api.migrations;
7817
8514
  const report = await runAddonMigrations({
7818
8515
  declareOwner: (input) => api.declareOwner.mutate(input),
7819
8516
  startMigration: (input) => api.startMigration.mutate(input),
7820
8517
  finishMigration: (input) => api.finishMigration.mutate(input)
7821
- }, migrations, this.ctx.logger, options);
8518
+ }, migrations, this.ctx.logger, phased);
7822
8519
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7823
8520
  return report;
7824
8521
  }
@@ -8891,237 +9588,6 @@ function normalizeAddonInitResult(result) {
8891
9588
  if (Array.isArray(result)) return { providers: result };
8892
9589
  return result;
8893
9590
  }
8894
- var PREFIX = "records/";
8895
- /** The base of every records failure. `detail` is the human part of the message. */
8896
- var RecordsError = class extends Error {
8897
- code;
8898
- detail;
8899
- constructor(code, detail) {
8900
- super(`${PREFIX}${code}: ${detail}`);
8901
- this.name = "RecordsError";
8902
- this.code = code;
8903
- this.detail = detail;
8904
- }
8905
- };
8906
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8907
- var RevConflictError = class extends RecordsError {
8908
- constructor(detail) {
8909
- super("rev-conflict", detail);
8910
- this.name = "RevConflictError";
8911
- }
8912
- };
8913
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8914
- var RecordSecretUnavailableError = class extends RecordsError {
8915
- constructor(detail) {
8916
- super("secret-unavailable", detail);
8917
- this.name = "RecordSecretUnavailableError";
8918
- }
8919
- };
8920
- var InvalidRecordError = class extends RecordsError {
8921
- constructor(detail) {
8922
- super("invalid-record", detail);
8923
- this.name = "InvalidRecordError";
8924
- }
8925
- };
8926
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8927
- var DeclarationRefusedError = class extends RecordsError {
8928
- constructor(detail) {
8929
- super("declaration-refused", detail);
8930
- this.name = "DeclarationRefusedError";
8931
- }
8932
- };
8933
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8934
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8935
- var RECORD_DATABASES = ["settings", "events"];
8936
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8937
- var RECORD_CLASSES = [
8938
- "config",
8939
- "ledger",
8940
- "audit",
8941
- "mirror",
8942
- "ephemeral"
8943
- ];
8944
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8945
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8946
- var RECORD_BATCH_MAX = 1e3;
8947
- var RECORD_QUERY_MAX = 1e3;
8948
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8949
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8950
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8951
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8952
- /**
8953
- * Secret fields of a record, addressed the way a Zod schema declares them
8954
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8955
- * (`auth.accessToken`, `headers[].value`).
8956
- *
8957
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8958
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8959
- * key releases exactly that key's secret.
8960
- *
8961
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8962
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8963
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8964
- * leaf names its element: `headers[X-Api].value`.
8965
- *
8966
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8967
- */
8968
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8969
- function parseSecretPath(path) {
8970
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8971
- return path.split(".").map((raw) => {
8972
- const each = raw.endsWith("[]");
8973
- const map = raw.endsWith("{}");
8974
- const key = each || map ? raw.slice(0, -2) : raw;
8975
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8976
- return {
8977
- key,
8978
- each,
8979
- map
8980
- };
8981
- });
8982
- }
8983
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8984
- function secretArrayPrefixes(path) {
8985
- const segments = parseSecretPath(path);
8986
- const prefixes = [];
8987
- const walked = [];
8988
- for (const segment of segments) {
8989
- walked.push(segment.key);
8990
- if (segment.each) prefixes.push(walked.join("."));
8991
- }
8992
- return prefixes;
8993
- }
8994
- function isRecord$4(value) {
8995
- return typeof value === "object" && value !== null && !Array.isArray(value);
8996
- }
8997
- function elementId(element, idKey, declared, prefix) {
8998
- const id = isRecord$4(element) ? element[idKey] : void 0;
8999
- 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`);
9000
- return id;
9001
- }
9002
- /**
9003
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9004
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9005
- * result is a new body, `data` is untouched.
9006
- */
9007
- var REMOVE_LEAF = Symbol("remove-leaf");
9008
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9009
- if (!isRecord$4(node)) return node;
9010
- const segment = segments[index];
9011
- if (segment === void 0) return node;
9012
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9013
- const child = node[segment.key];
9014
- const keys = [...walkedKeys, segment.key];
9015
- const last = index === segments.length - 1;
9016
- if (segment.each) {
9017
- if (!Array.isArray(child)) return node;
9018
- const prefix = keys.join(".");
9019
- const idKey = arrayKeys[prefix];
9020
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9021
- const mapped = child.map((element) => {
9022
- const id = elementId(element, idKey, declared, prefix);
9023
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9024
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9025
- });
9026
- return {
9027
- ...node,
9028
- [segment.key]: mapped
9029
- };
9030
- }
9031
- if (segment.map) {
9032
- if (!isRecord$4(child)) return node;
9033
- const kept = Object.entries(child).map(([mapKey, value]) => {
9034
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9035
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9036
- return [mapKey, visit({
9037
- declared,
9038
- concrete,
9039
- value
9040
- })];
9041
- }).filter(([, value]) => value !== REMOVE_LEAF);
9042
- return {
9043
- ...node,
9044
- [segment.key]: Object.fromEntries(kept)
9045
- };
9046
- }
9047
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9048
- if (last) {
9049
- const replacement = visit({
9050
- declared,
9051
- concrete,
9052
- value: child
9053
- });
9054
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9055
- return {
9056
- ...node,
9057
- [segment.key]: replacement
9058
- };
9059
- }
9060
- return {
9061
- ...node,
9062
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9063
- };
9064
- }
9065
- /** Replace/remove every present secret leaf; returns a NEW body. */
9066
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9067
- let current = data;
9068
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9069
- return current;
9070
- }
9071
- /** Every present secret leaf, read-only. */
9072
- function collectSecretLeaves(data, paths, arrayKeys) {
9073
- const found = [];
9074
- mapSecretLeaves(data, paths, arrayKeys, (leaf) => {
9075
- found.push(leaf);
9076
- return leaf.value;
9077
- });
9078
- return found;
9079
- }
9080
- /**
9081
- * The keychain collection name a kind's secrets live under. Prefixed so a
9082
- * record's refs never collide with the refs a legacy collection of the same name
9083
- * already holds during an adoption.
9084
- */
9085
- function recordSecretCollection(kind) {
9086
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9087
- }
9088
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9089
- function recordSecretRef(owner, kind, rowId, concretePath) {
9090
- return buildSecretRef({
9091
- owner,
9092
- scope: {
9093
- kind: "row",
9094
- collection: recordSecretCollection(kind),
9095
- rowId
9096
- },
9097
- fieldPath: concretePath
9098
- });
9099
- }
9100
- /**
9101
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9102
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9103
- * token. The form hands it to the secret field, which reveals the value by ref
9104
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9105
- * stored secret (the records door reads a view as KEEP).
9106
- *
9107
- * ONE implementation for the entries service and for every addon that serves
9108
- * its own instances (`RecordIntegrationInstances`).
9109
- */
9110
- function isRecord$3(value) {
9111
- return typeof value === "object" && value !== null && !Array.isArray(value);
9112
- }
9113
- function secretViewsOf(owner, kind, id, decl, data) {
9114
- if (decl.secretPaths.length === 0) return data;
9115
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9116
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9117
- return {
9118
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9119
- v: 1,
9120
- set: true
9121
- };
9122
- });
9123
- return isRecord$3(shown) ? shown : data;
9124
- }
9125
9591
  /**
9126
9592
  * The share-view scope kinds a share-link token can carry. The hub mints
9127
9593
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9375,6 +9841,7 @@ function defineRecordKinds(specs) {
9375
9841
  function entryBody(shape) {
9376
9842
  return object({
9377
9843
  name: string().min(1),
9844
+ enabled: boolean().optional(),
9378
9845
  ...shape
9379
9846
  });
9380
9847
  }
@@ -11218,6 +11685,10 @@ Object.freeze({
11218
11685
  "all",
11219
11686
  "one"
11220
11687
  ]
11688
+ },
11689
+ {
11690
+ "path": "positionUpdatedAt",
11691
+ "valueType": "number"
11221
11692
  }
11222
11693
  ],
11223
11694
  "meter": [{
@@ -11472,22 +11943,6 @@ Object.freeze({
11472
11943
  "path": "pumpRunning",
11473
11944
  "valueType": "boolean"
11474
11945
  },
11475
- {
11476
- "path": "lastDrink",
11477
- "valueType": "number"
11478
- },
11479
- {
11480
- "path": "currentHourDrink",
11481
- "valueType": "number"
11482
- },
11483
- {
11484
- "path": "last24hDrink",
11485
- "valueType": "number"
11486
- },
11487
- {
11488
- "path": "todayDrink",
11489
- "valueType": "number"
11490
- },
11491
11946
  {
11492
11947
  "path": "error",
11493
11948
  "valueType": "string"
@@ -12053,12 +12508,66 @@ Object.freeze({
12053
12508
  }
12054
12509
  ]
12055
12510
  });
12511
+ Object.freeze({
12512
+ "actions": { "run": 363e4 },
12513
+ "audio-analyzer": { "classify": 3e4 },
12514
+ "custom-model-registry": { "importModelBundle": 18e5 },
12515
+ "database-snapshot": { "writeSnapshot": 18e5 },
12516
+ "device-manager": {
12517
+ "migrateDevice": 72e4,
12518
+ "runDiscoverySweep": 12e4
12519
+ },
12520
+ "device-provider": { "reloadDevice": 18e4 },
12521
+ "llm": {
12522
+ "generate": 6e5,
12523
+ "generateVision": 6e5,
12524
+ "testProfile": 6e5
12525
+ },
12526
+ "llm-runtime": {
12527
+ "complete": 6e5,
12528
+ "completeApple": 6e5,
12529
+ "ensureStarted": 6e5,
12530
+ "installModel": 36e5
12531
+ },
12532
+ "local-network": { "scanNetwork": 9e4 },
12533
+ "model-convert": { "convert": 6e5 },
12534
+ "pipeline-analytics": {
12535
+ "addRetrainFrameFromRecording": 6e4,
12536
+ "offerRetrainArchive": 12e4,
12537
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12538
+ "resolveRetrainTrainingCorpus": 6e4,
12539
+ "writeRetrainArchive": 36e5
12540
+ },
12541
+ "server-management": { "applyServerUpdate": 96e4 },
12542
+ "terminal-session": { "pullOutput": 15e3 },
12543
+ "training": {
12544
+ "canaryResult": 12e4,
12545
+ "cancelJob": 12e4,
12546
+ "planJob": 6e4,
12547
+ "registerResult": 18e5,
12548
+ "rollbackCanary": 12e4,
12549
+ "startJob": 12e4,
12550
+ "startJobBatch": 12e4
12551
+ },
12552
+ "training-provider": {
12553
+ "cancelJob": 6e4,
12554
+ "cleanupJob": 3e5,
12555
+ "getJob": 6e4,
12556
+ "listJobEvents": 6e4,
12557
+ "listJobs": 12e4,
12558
+ "offerArtifact": 3e5,
12559
+ "readResult": 3e5,
12560
+ "submitJob": 18e5,
12561
+ "uploadDataset": 72e5,
12562
+ "validateCredentials": 3e4
12563
+ }
12564
+ });
12056
12565
  object({
12057
12566
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12058
12567
  params: record(string(), union([string(), number()])).optional()
12059
12568
  });
12060
12569
  //#endregion
12061
- //#region ../types/dist/composition-pOHbTzRB.mjs
12570
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12062
12571
  /**
12063
12572
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12064
12573
  *
@@ -12362,7 +12871,7 @@ var table = {
12362
12871
  },
12363
12872
  dwell: {
12364
12873
  minArgs: 3,
12365
- maxArgs: 3,
12874
+ maxArgs: 4,
12366
12875
  apply: () => {
12367
12876
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12368
12877
  }
@@ -13405,212 +13914,6 @@ var IntegrationInstanceRefSchema = object({
13405
13914
  ]),
13406
13915
  candidateStableId: string().optional()
13407
13916
  });
13408
- /**
13409
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13410
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13411
- *
13412
- * Every instance is one record of the addon's own kind, keyed by the
13413
- * `integrations` registry id. The records door does the secret work: a field the
13414
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13415
- * deleting the row deletes the secret, and one row's value is never another's.
13416
- *
13417
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13418
- * token or the view the form was given KEEP the stored secret;
13419
- * `{ $secretClear: true }` clears it; any other string replaces it.
13420
- */
13421
- /** The most instances one addon lists (an integrations page, not a table). */
13422
- var INSTANCES_LIST_MAX = 1e3;
13423
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13424
- function topLevelSecretKeys(paths) {
13425
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13426
- }
13427
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13428
- function secretMapKeys(paths) {
13429
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13430
- }
13431
- /**
13432
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13433
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13434
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13435
- */
13436
- function secretMapPatch(value) {
13437
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13438
- const out = {};
13439
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13440
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13441
- return Object.keys(out).length > 0 ? out : null;
13442
- }
13443
- /** Does the kind's body schema carry an `enabled` field? */
13444
- function declaresEnabled(kind) {
13445
- const json = toJSONSchema(kind.schema, {
13446
- unrepresentable: "any",
13447
- io: "input"
13448
- });
13449
- const properties = Reflect.get(json, "properties");
13450
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13451
- }
13452
- var RecordIntegrationInstances = class {
13453
- records;
13454
- kind;
13455
- hooks;
13456
- handle;
13457
- secretKeys;
13458
- secretMaps;
13459
- nameField;
13460
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13461
- registryOwnsEnabled;
13462
- constructor(records, kind, hooks) {
13463
- this.records = records;
13464
- this.kind = kind;
13465
- this.hooks = hooks;
13466
- this.handle = records.kind(kind);
13467
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13468
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13469
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13470
- this.registryOwnsEnabled = hooks.description.role === "devices";
13471
- 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"`);
13472
- }
13473
- /**
13474
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13475
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13476
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13477
- */
13478
- async readResolved(id) {
13479
- try {
13480
- const record = await this.handle.getResolved(id);
13481
- return record === null ? null : {
13482
- id,
13483
- body: record.data,
13484
- enabled: record.data.enabled !== false,
13485
- secrets: "resolved"
13486
- };
13487
- } catch (err) {
13488
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13489
- const stored = await this.handle.get(id);
13490
- if (stored === null) return null;
13491
- return {
13492
- id,
13493
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13494
- enabled: stored.data.enabled !== false,
13495
- secrets: "unavailable"
13496
- };
13497
- }
13498
- }
13499
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13500
- async getResolved(id) {
13501
- return (await this.readResolved(id))?.body ?? null;
13502
- }
13503
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13504
- async listResolved() {
13505
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13506
- const out = [];
13507
- for (const record of page.records) {
13508
- const read = await this.readResolved(record.id);
13509
- if (read !== null) out.push(read);
13510
- }
13511
- return out;
13512
- }
13513
- viewOf(record) {
13514
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13515
- const rawName = record.data[this.nameField];
13516
- const kind = this.hooks.kindOf?.(record.data);
13517
- const health = this.hooks.health?.(record.data, record.id);
13518
- return {
13519
- id: record.id,
13520
- name: typeof rawName === "string" ? rawName : record.id,
13521
- configured: this.hooks.configured(record.data),
13522
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13523
- formValues: shown,
13524
- ...kind !== void 0 ? { kind } : {},
13525
- ...health?.status !== void 0 ? { status: health.status } : {},
13526
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13527
- };
13528
- }
13529
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13530
- ...this.hooks.description,
13531
- mintsId: true
13532
- };
13533
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13534
- listInstances = async () => {
13535
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13536
- };
13537
- getInstance = async ({ id }) => {
13538
- const record = await this.handle.get(id);
13539
- return record === null ? null : this.viewOf(record);
13540
- };
13541
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13542
- createInstance = async ({ id, name, kind, values }) => {
13543
- const minted = id ?? this.hooks.mintId?.({
13544
- name,
13545
- ...kind !== void 0 ? { kind } : {}
13546
- });
13547
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13548
- await this.handle.put({
13549
- id: minted,
13550
- data: this.hooks.initialBody(name, kind)
13551
- }, { ifRev: 0 });
13552
- const patch = this.patchOf(values ?? {});
13553
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13554
- await this.hooks.onChanged?.(minted, "created");
13555
- return { id: minted };
13556
- };
13557
- updateInstance = async ({ id, name, values }) => {
13558
- const patch = this.patchOf(values);
13559
- if (name !== void 0) patch[this.nameField] = name;
13560
- await this.handle.patch(id, patch);
13561
- await this.hooks.onChanged?.(id, "updated");
13562
- return { ok: true };
13563
- };
13564
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13565
- patchOf(values) {
13566
- const patch = {};
13567
- for (const [key, value] of Object.entries(values)) {
13568
- if (value === void 0) continue;
13569
- if (this.secretMaps.has(key)) {
13570
- const entries = secretMapPatch(value);
13571
- if (entries !== null) patch[key] = entries;
13572
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13573
- else if (isSecretClear(value)) patch[key] = null;
13574
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13575
- }
13576
- return patch;
13577
- }
13578
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13579
- setInstanceEnabled = async ({ id, enabled }) => {
13580
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13581
- await this.handle.patch(id, { enabled });
13582
- await this.hooks.onChanged?.(id, "enabled");
13583
- return { ok: true };
13584
- };
13585
- /** The row and its keychain refs go together (the records door). */
13586
- deleteInstance = async ({ id }) => {
13587
- await this.handle.delete(id);
13588
- await this.hooks.onChanged?.(id, "deleted");
13589
- return { ok: true };
13590
- };
13591
- testInstance = async (input) => {
13592
- if (this.hooks.test === void 0) return {
13593
- success: false,
13594
- status: "unsupported",
13595
- error: "This integration declares no connection test"
13596
- };
13597
- return this.hooks.test(input);
13598
- };
13599
- /** The flat provider object to hand to `registerProvider`. */
13600
- toProvider() {
13601
- return {
13602
- describe: this.describe,
13603
- instanceFormSchema: this.instanceFormSchema,
13604
- listInstances: this.listInstances,
13605
- getInstance: this.getInstance,
13606
- createInstance: this.createInstance,
13607
- updateInstance: this.updateInstance,
13608
- setInstanceEnabled: this.setInstanceEnabled,
13609
- deleteInstance: this.deleteInstance,
13610
- testInstance: this.testInstance
13611
- };
13612
- }
13613
- };
13614
13917
  var EncodeProfileSchema = object({
13615
13918
  video: object({
13616
13919
  codec: _enum([
@@ -19992,31 +20295,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19992
20295
  "pet-fountain": {
19993
20296
  scope: "device",
19994
20297
  noun: t("Pet fountain", "Fontana per animali"),
19995
- actions: [
19996
- {
19997
- id: "petFountain.pumpOn",
19998
- method: "setPump",
19999
- label: t("Pump on", "Pompa accesa"),
20000
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20001
- icon: "play",
20002
- args: { on: true }
20003
- },
20004
- {
20005
- id: "petFountain.pumpOff",
20006
- method: "setPump",
20007
- label: t("Pump off", "Pompa spenta"),
20008
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20009
- icon: "square",
20010
- args: { on: false }
20011
- },
20012
- {
20013
- id: "petFountain.resetDailyConsumption",
20014
- method: "resetDailyConsumption",
20015
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
20016
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
20017
- icon: "rotate-ccw"
20018
- }
20019
- ],
20298
+ actions: [{
20299
+ id: "petFountain.pumpOn",
20300
+ method: "setPump",
20301
+ label: t("Pump on", "Pompa accesa"),
20302
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20303
+ icon: "play",
20304
+ args: { on: true }
20305
+ }, {
20306
+ id: "petFountain.pumpOff",
20307
+ method: "setPump",
20308
+ label: t("Pump off", "Pompa spenta"),
20309
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20310
+ icon: "square",
20311
+ args: { on: false }
20312
+ }],
20020
20313
  state: [{
20021
20314
  kind: "boolean",
20022
20315
  field: "empty",
@@ -44049,8 +44342,15 @@ var ActionInputSchema = object({
44049
44342
  var ActionRunOriginSchema = object({
44050
44343
  /** The automation block whose step started it. */
44051
44344
  blockId: string().min(1).optional() });
44052
- /** `started` = the caller did not ask to wait. */
44053
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44345
+ /**
44346
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44347
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44348
+ */
44349
+ var ActionRunOutcomeSchema = union([
44350
+ AutomationRunOutcomeSchema,
44351
+ literal("started"),
44352
+ literal("timed-out")
44353
+ ]);
44054
44354
  var ActionRunResultSchema = object({
44055
44355
  runId: string().min(1),
44056
44356
  outcome: ActionRunOutcomeSchema,
@@ -44572,6 +44872,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44572
44872
  kind: "mutation",
44573
44873
  auth: "admin"
44574
44874
  });
44875
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44876
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44575
44877
  /**
44576
44878
  * actions — the ONE surface for runnable actions, for the UI and for
44577
44879
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44590,6 +44892,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44590
44892
  * An admin, and an in-process caller (an automation block), may run any action.
44591
44893
  * Every refusal is typed (`[not-linked] …`) and logged.
44592
44894
  *
44895
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44896
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44897
+ * `wait` steps alone add up to more is refused at create/update
44898
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44899
+ * waited call (an automation step) is never cut by the 60 s transport default.
44900
+ *
44593
44901
  * A second `run` of an action that is already running is REFUSED — traced and
44594
44902
  * logged — never queued.
44595
44903
  */
@@ -44616,7 +44924,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44616
44924
  role: "viewer",
44617
44925
  auth: "protected",
44618
44926
  kind: "mutation",
44619
- caller: "required"
44927
+ caller: "required",
44928
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44620
44929
  }), method(ActionIdInput, _void(), {
44621
44930
  kind: "mutation",
44622
44931
  auth: "admin"
@@ -49643,6 +49952,9 @@ var MediaPlayerStatusSchema = object({
49643
49952
  /** Repeat mode. Null when no repeat surface.
49644
49953
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
49645
49954
  repeat: MediaPlayerRepeatSchema.nullable(),
49955
+ /** Ms epoch when `position` was read from the device. Null when the driver
49956
+ * does not say; a UI that advances the position while playing counts from it. */
49957
+ positionUpdatedAt: number().nullable().default(null),
49646
49958
  /** Ms epoch when the slice was last updated. */
49647
49959
  lastChangedAt: number()
49648
49960
  });
@@ -50278,7 +50590,9 @@ var ThresholdTransformDraftSchema = object({
50278
50590
  comparison: _enum(["gte", "lte"]),
50279
50591
  threshold: number(),
50280
50592
  startDwellMs: number().nonnegative(),
50281
- stopDwellMs: number().nonnegative()
50593
+ stopDwellMs: number().nonnegative(),
50594
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
50595
+ minSamples: number().int().min(1).optional()
50282
50596
  });
50283
50597
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
50284
50598
  IdentityTransformDraftSchema,
@@ -56176,6 +56490,7 @@ var IntegrationWithStateSchema = object({
56176
56490
  id: string(),
56177
56491
  addonId: string(),
56178
56492
  name: string(),
56493
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56179
56494
  enabled: boolean(),
56180
56495
  info: record(string(), unknown()).readonly(),
56181
56496
  /** The discovery candidate this integration was set up from (D984). */
@@ -56188,6 +56503,7 @@ var IntegrationLiteSchema = object({
56188
56503
  id: string(),
56189
56504
  addonId: string(),
56190
56505
  name: string(),
56506
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
56191
56507
  enabled: boolean(),
56192
56508
  info: record(string(), unknown()).readonly(),
56193
56509
  /** The discovery candidate this integration was set up from (D984). */
@@ -56287,7 +56603,6 @@ var TestConnectionResultSchema = object({
56287
56603
  var CreateIntegrationInputSchema = object({
56288
56604
  addonId: string(),
56289
56605
  name: string(),
56290
- enabled: boolean().optional(),
56291
56606
  info: record(string(), unknown()).optional(),
56292
56607
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
56293
56608
  originStableId: string().optional(),
@@ -56296,6 +56611,11 @@ var CreateIntegrationInputSchema = object({
56296
56611
  var UpdateIntegrationInputSchema = object({
56297
56612
  id: string(),
56298
56613
  name: string().optional(),
56614
+ /**
56615
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
56616
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
56617
+ * integration is switched through `integration-instances.setInstanceEnabled`.
56618
+ */
56299
56619
  enabled: boolean().optional(),
56300
56620
  info: record(string(), unknown()).optional()
56301
56621
  });
@@ -56343,7 +56663,7 @@ var IntegrationInstanceIdSchema = string().min(1);
56343
56663
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
56344
56664
  /**
56345
56665
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
56346
- * instance is an integration that brings devices (the registry owns its on/off switch);
56666
+ * instance is an integration that brings devices (its record body owns the on/off switch);
56347
56667
  * `services`: a connection configured from the addon's own function page, never listed on
56348
56668
  * Integrations.
56349
56669
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -56386,18 +56706,38 @@ var IntegrationInstanceKindSchema = object({
56386
56706
  /** Relative hub path to disconnect that account. */
56387
56707
  disconnectPath: string().min(1).optional()
56388
56708
  });
56709
+ /**
56710
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
56711
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
56712
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
56713
+ * instance and its candidates are claimed by it.
56714
+ */
56715
+ var IntegrationInstanceDiscoverySchema = object({
56716
+ mode: _enum([
56717
+ "none",
56718
+ "lan",
56719
+ "account"
56720
+ ]),
56721
+ scopedToInstance: boolean()
56722
+ });
56723
+ /**
56724
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
56725
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
56726
+ * The hub indexes these so the target's delete is refused while a link names it.
56727
+ */
56728
+ var IntegrationInstanceLinkSchema = object({
56729
+ kind: string().min(1),
56730
+ field: string().min(1),
56731
+ to: object({
56732
+ cap: string().min(1),
56733
+ kind: string().min(1).optional()
56734
+ })
56735
+ });
56389
56736
  var IntegrationInstanceDescriptionSchema = object({
56390
56737
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
56391
56738
  role: IntegrationInstanceRoleSchema,
56392
56739
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
56393
- discovery: object({
56394
- mode: _enum([
56395
- "none",
56396
- "lan",
56397
- "account"
56398
- ]),
56399
- scopedToInstance: boolean()
56400
- }).optional(),
56740
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
56401
56741
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
56402
56742
  instanceMode: IntegrationInstanceModeSchema,
56403
56743
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -56418,7 +56758,9 @@ var IntegrationInstanceDescriptionSchema = object({
56418
56758
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
56419
56759
  * send an id (the UI then mints an opaque one).
56420
56760
  */
56421
- mintsId: boolean().optional()
56761
+ mintsId: boolean().optional(),
56762
+ /** The links to other instances the provider's kinds declare; absent means none. */
56763
+ links: array(IntegrationInstanceLinkSchema).optional()
56422
56764
  });
56423
56765
  var IntegrationInstanceStatusSchema = object({
56424
56766
  state: _enum([
@@ -56438,8 +56780,8 @@ var IntegrationInstanceSchema = object({
56438
56780
  configured: boolean(),
56439
56781
  /**
56440
56782
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
56441
- * so a row written before the field existed is on). Absent when the `integrations` registry
56442
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
56783
+ * so a row written before the field existed is on). The same for every role, `devices` included:
56784
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
56443
56785
  */
56444
56786
  enabled: boolean().optional(),
56445
56787
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -56489,7 +56831,8 @@ var integrationInstancesCapability = {
56489
56831
  auth: "admin"
56490
56832
  }),
56491
56833
  /**
56492
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
56834
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
56835
+ * initial body. A row control, not a form field: `updateInstance.values` is the
56493
56836
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
56494
56837
  */
56495
56838
  setInstanceEnabled: method(object({
@@ -59552,6 +59895,8 @@ var MigrationIntegrationSchema = object({
59552
59895
  addonId: string(),
59553
59896
  name: string(),
59554
59897
  info: Rows,
59898
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
59899
+ enabled: boolean().optional(),
59555
59900
  originStableId: string().optional()
59556
59901
  });
59557
59902
  var MigrationDeviceSchema = object({
@@ -69681,14 +70026,6 @@ var PetFountainStatusSchema = object({
69681
70026
  empty: boolean().nullable(),
69682
70027
  /** True while the pump is running. Null while unknown. */
69683
70028
  pumpRunning: boolean().nullable(),
69684
- /** Water drunk in the last drink, in litres. */
69685
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
69686
- /** Water drunk in the current hour, in litres. */
69687
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
69688
- /** Water drunk over the last 24 hours (rolling), in litres. */
69689
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
69690
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
69691
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
69692
70029
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
69693
70030
  error: string().nullable(),
69694
70031
  /** Ms epoch when the slice was last refreshed. */
@@ -69701,21 +70038,15 @@ var petFountainCapability = {
69701
70038
  deviceNative: true,
69702
70039
  mode: "singleton",
69703
70040
  deviceTypes: [DeviceType.PetFountain],
69704
- methods: {
69705
- /** Start or stop the pump. */
69706
- setPump: method(object({
69707
- deviceId: DeviceIdSchema$1,
69708
- on: boolean()
69709
- }), _void(), {
69710
- kind: "mutation",
69711
- auth: "protected"
69712
- }),
69713
- /** Clear the rolling daily consumption counters on the device. */
69714
- resetDailyConsumption: method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
69715
- kind: "mutation",
69716
- auth: "protected"
69717
- })
69718
- },
70041
+ methods: {
70042
+ /** Start or stop the pump. */
70043
+ setPump: method(object({
70044
+ deviceId: DeviceIdSchema$1,
70045
+ on: boolean()
70046
+ }), _void(), {
70047
+ kind: "mutation",
70048
+ auth: "protected"
70049
+ }) },
69719
70050
  status: {
69720
70051
  schema: PetFountainStatusSchema,
69721
70052
  kind: "push"
@@ -69739,14 +70070,6 @@ var petFountainCapability = {
69739
70070
  waterVolume: {
69740
70071
  kind: "gauge",
69741
70072
  unit: "L"
69742
- },
69743
- todayDrink: {
69744
- kind: "gauge",
69745
- unit: "L"
69746
- },
69747
- last24hDrink: {
69748
- kind: "gauge",
69749
- unit: "L"
69750
70073
  }
69751
70074
  } }
69752
70075
  };
@@ -88287,13 +88610,6 @@ Object.freeze({
88287
88610
  access: "view",
88288
88611
  role: "viewer"
88289
88612
  },
88290
- "petFountain.resetDailyConsumption": {
88291
- capName: "pet-fountain",
88292
- capScope: "device",
88293
- addonId: null,
88294
- access: "delete",
88295
- role: "viewer"
88296
- },
88297
88613
  "petFountain.setPump": {
88298
88614
  capName: "pet-fountain",
88299
88615
  capScope: "device",
@@ -94690,11 +95006,6 @@ Object.freeze({
94690
95006
  form: "single",
94691
95007
  optional: false
94692
95008
  }],
94693
- "petFountain.resetDailyConsumption": [{
94694
- name: "deviceId",
94695
- form: "single",
94696
- optional: false
94697
- }],
94698
95009
  "petFountain.setPump": [{
94699
95010
  name: "deviceId",
94700
95011
  form: "single",
@@ -97563,74 +97874,6 @@ object({
97563
97874
  delay: number().nonnegative().optional(),
97564
97875
  commands: record(string(), unknown())
97565
97876
  });
97566
- entryBody({ brokerId: string() });
97567
- function secretsOverMigrationApi(api) {
97568
- return {
97569
- resolve: async (refs) => {
97570
- const { values } = await api.secrets.resolve({ refs: [...refs] });
97571
- const out = {};
97572
- for (const ref of refs) {
97573
- const value = values[ref];
97574
- out[ref] = value === null || value === void 0 ? { kind: "missing" } : {
97575
- kind: "value",
97576
- value,
97577
- version: 0
97578
- };
97579
- }
97580
- return out;
97581
- },
97582
- delete: async (refs) => (await api.secrets.delete({ refs: [...refs] })).deleted
97583
- };
97584
- }
97585
- /** `ctx.records` as the migration API offers it: bind a kind, read and write by id. */
97586
- function recordsOverMigrationApi(api) {
97587
- return { kind: (definition) => {
97588
- const handle = api.records.kind(definition);
97589
- return {
97590
- get: (id) => handle.get({ id }),
97591
- getResolved: (id) => handle.getResolved({ id }),
97592
- put: (input, opts) => handle.put({
97593
- ...input,
97594
- ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
97595
- }),
97596
- delete: (id) => handle.delete({ id })
97597
- };
97598
- } };
97599
- }
97600
- function integrationRowsApiOver(api) {
97601
- return {
97602
- list: async () => (await api.integrations.list({})).integrations,
97603
- readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
97604
- clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
97605
- };
97606
- }
97607
- /**
97608
- * One serial lane per migration API: a log line is delivered after the line before it, so the
97609
- * order the steps wrote them in is the order the hub reads them in. A delivery that fails
97610
- * is reported once through the same door; if that fails too nothing is left to tell, and the
97611
- * line is dropped rather than thrown into a migration step or left as an unhandled rejection.
97612
- */
97613
- var lanes = /* @__PURE__ */ new WeakMap();
97614
- function deliver(api, send) {
97615
- const next = (lanes.get(api) ?? Promise.resolve()).then(send).then(() => void 0).catch(async (error) => {
97616
- const reason = error instanceof Error ? error.message : String(error);
97617
- await api.log.warn({ message: `a migration log line could not be delivered: ${reason}` }).catch(() => void 0);
97618
- });
97619
- lanes.set(api, next);
97620
- return next;
97621
- }
97622
- function warnOver(api) {
97623
- return (message) => deliver(api, () => api.log.warn({ message }));
97624
- }
97625
- /** What the rows-to-records move needs, over the migration API. */
97626
- function rowsDepsOver(api) {
97627
- return {
97628
- api: integrationRowsApiOver(api),
97629
- records: recordsOverMigrationApi(api),
97630
- secrets: secretsOverMigrationApi(api),
97631
- warn: warnOver(api)
97632
- };
97633
- }
97634
97877
  //#endregion
97635
97878
  //#region src/config.ts
97636
97879
  /**
@@ -99399,6 +99642,10 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99399
99642
  const records = this.ctx.records;
99400
99643
  if (records === void 0) throw new Error("provider-enpal: ctx.records is required (hub-only addon)");
99401
99644
  await records.declare(enpalRecordKinds);
99645
+ this.declareRegistrySwitch({
99646
+ kind: enpalConnectionsEntryKind,
99647
+ initialBody: (name) => ({ name })
99648
+ });
99402
99649
  await this.runMigrations([integrationRowsMigration({
99403
99650
  addonId: this.addonId,
99404
99651
  date: ENPAL_MIGRATIONS_DATE,
@@ -99489,8 +99736,9 @@ var EnpalProviderAddon = class extends BaseDeviceProvider {
99489
99736
  const integrationId = event.data["integrationId"];
99490
99737
  this.reconciler().onLifecycle(kind, typeof integrationId === "string" ? integrationId : null);
99491
99738
  };
99492
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, on("enabled"));
99493
- this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, on("disabled"));
99739
+ this.requireInstances().onSwitched((id, enabled) => {
99740
+ this.reconciler().onLifecycle(enabled ? "enabled" : "disabled", id);
99741
+ });
99494
99742
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, on("deleted"));
99495
99743
  }
99496
99744
  /** The integrations that own devices here, for the orphan sweep. */