@camstack/addon-smtp-nodemailer 1.2.149 → 1.2.150

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.
@@ -6020,7 +6020,7 @@ var ZodIssueCode = {
6020
6020
  var ZodFirstPartyTypeKind;
6021
6021
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6022
6022
  //#endregion
6023
- //#region ../types/dist/sleep-BX_MqzUe.mjs
6023
+ //#region ../types/dist/sleep-CmjWurK5.mjs
6024
6024
  /**
6025
6025
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6026
6026
  * window to float samples (D455).
@@ -6704,137 +6704,93 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6704
6704
  blockOwner
6705
6705
  };
6706
6706
  }
6707
- /**
6708
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6709
- * `read`/`write` are the addon-store or device-store accessors. The whole
6710
- * validated value round-trips on every read/write — the schema is the
6711
- * single source of truth for what is persisted, so no hand-listed field
6712
- * set can drop a key on save.
6713
- */
6714
- function createDurableState(deps) {
6715
- const get = async () => {
6716
- const raw = (await deps.read())[deps.key];
6717
- if (raw === void 0) return deps.fallback;
6718
- const parsed = deps.schema.safeParse(raw);
6719
- if (!parsed.success) {
6720
- deps.onParseError?.(deps.key, parsed.error);
6721
- return deps.fallback;
6722
- }
6723
- return parsed.data;
6724
- };
6725
- const set = async (next) => {
6726
- const validated = deps.schema.parse(next);
6727
- await deps.write({ [deps.key]: validated });
6728
- };
6729
- const update = async (fn) => {
6730
- await set(fn(await get()));
6731
- };
6707
+ /** The record calls the one-switch migration makes, over the migration API. */
6708
+ function switchRecordsOverMigrationApi(api) {
6709
+ return { kind: (definition) => {
6710
+ const handle = api.records.kind(definition);
6711
+ return {
6712
+ get: (id) => handle.get({ id }),
6713
+ put: (input, opts) => handle.put({
6714
+ ...input,
6715
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6716
+ }),
6717
+ patch: (id, partial) => handle.patch({
6718
+ id,
6719
+ partial
6720
+ })
6721
+ };
6722
+ } };
6723
+ }
6724
+ function integrationRowsApiOver(api) {
6732
6725
  return {
6733
- get,
6734
- set,
6735
- update
6726
+ list: async () => (await api.integrations.list({})).integrations,
6727
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6728
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6736
6729
  };
6737
6730
  }
6738
- /**
6739
- * Per-node scoping for the shared addon-settings blob.
6740
- *
6741
- * An addon's settings store is hub-central (the `addon-settings` cap is
6742
- * hub-routed — the hub instance answers for every node), so fields whose
6743
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6744
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6745
- * the single shared blob. The SCHEMA field key stays bare: the write path
6746
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6747
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6748
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6749
- *
6750
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6751
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6752
- * schema and routes reads/writes through these helpers.
6753
- *
6754
- * ## No bare-key fallback — deliberate
6755
- *
6756
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6757
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6758
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6759
- * the store is invisible to every node, hub included, so one node's
6760
- * selection can never leak onto another. (This generalizes the
6761
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6762
- * arbitrary set of per-node field keys.)
6763
- *
6764
- * Pure functions only — no I/O, no imports beyond the language. This is a
6765
- * LEAF module: import it via its deep path, never from the root barrel.
6766
- */
6767
- /**
6768
- * Normalize a raw kernel node id to the bare node id used for scoping.
6769
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6770
- * processes; per-node settings are per-NODE, so strip the addon segment.
6771
- * `undefined` / `null` / empty falls back to `'hub'`.
6772
- */
6773
- function normalizeNodeId(raw) {
6774
- if (raw === void 0 || raw === null || raw === "") return "hub";
6775
- const slashIdx = raw.indexOf("/");
6776
- if (slashIdx < 0) return raw;
6777
- const bare = raw.slice(0, slashIdx);
6778
- return bare === "" ? "hub" : bare;
6779
- }
6780
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6781
- function nodeScopedKey(base, nodeId) {
6782
- return `${base}@${normalizeNodeId(nodeId)}`;
6783
- }
6784
- /**
6785
- * Read a node's value for a per-node field from the raw shared store:
6786
- * the node-scoped key when present, otherwise `undefined`.
6787
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6788
- * schema `default` win on `undefined`.
6789
- */
6790
- function readNodeValue(store, base, nodeId) {
6791
- return store[nodeScopedKey(base, nodeId)];
6792
- }
6793
- /**
6794
- * Re-map a UI/settings patch so every bare perNode field persists under the
6795
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6796
- * the write path so a save for one node never clobbers another node's value
6797
- * (and the bare key is never written). Returns a new object — the input
6798
- * patch is not mutated.
6799
- */
6800
- function scopePatch(patch, perNodeKeys, nodeId) {
6801
- const out = {};
6802
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6803
- return out;
6804
- }
6805
- /**
6806
- * Project the raw shared store onto the bare schema keys for ONE node so a
6807
- * UI schema (whose field keys are bare) hydrates from that node's own
6808
- * values:
6809
- *
6810
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6811
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6812
- * legacy key must never hydrate any node — no bare fallback).
6813
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6814
- * each bare perNode key; when the node has no scoped key the bare key is
6815
- * left ABSENT so the field's schema `default` wins.
6816
- *
6817
- * Returns a new object — the input store is not mutated.
6818
- */
6819
- function projectStore(store, perNodeKeys, nodeId) {
6820
- const out = {};
6821
- for (const [key, value] of Object.entries(store)) {
6822
- if (key.includes("@")) continue;
6823
- if (perNodeKeys.has(key)) continue;
6824
- out[key] = value;
6731
+ var PREFIX = "records/";
6732
+ /** The base of every records failure. `detail` is the human part of the message. */
6733
+ var RecordsError = class extends Error {
6734
+ code;
6735
+ detail;
6736
+ constructor(code, detail) {
6737
+ super(`${PREFIX}${code}: ${detail}`);
6738
+ this.name = "RecordsError";
6739
+ this.code = code;
6740
+ this.detail = detail;
6825
6741
  }
6826
- for (const base of perNodeKeys) {
6827
- const value = readNodeValue(store, base, nodeId);
6828
- if (value !== void 0) out[base] = value;
6742
+ };
6743
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6744
+ var RevConflictError = class extends RecordsError {
6745
+ constructor(detail) {
6746
+ super("rev-conflict", detail);
6747
+ this.name = "RevConflictError";
6829
6748
  }
6830
- return out;
6749
+ };
6750
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6751
+ var RecordSecretUnavailableError = class extends RecordsError {
6752
+ constructor(detail) {
6753
+ super("secret-unavailable", detail);
6754
+ this.name = "RecordSecretUnavailableError";
6755
+ }
6756
+ };
6757
+ var InvalidRecordError = class extends RecordsError {
6758
+ constructor(detail) {
6759
+ super("invalid-record", detail);
6760
+ this.name = "InvalidRecordError";
6761
+ }
6762
+ };
6763
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6764
+ var DeclarationRefusedError = class extends RecordsError {
6765
+ constructor(detail) {
6766
+ super("declaration-refused", detail);
6767
+ this.name = "DeclarationRefusedError";
6768
+ }
6769
+ };
6770
+ function linkTargetOf(meta) {
6771
+ if (typeof meta !== "object" || meta === null) return void 0;
6772
+ const link = Reflect.get(meta, "link");
6773
+ const parsed = LinkTargetSchema.safeParse(link);
6774
+ return parsed.success ? parsed.data : void 0;
6775
+ }
6776
+ var LinkTargetSchema = object({
6777
+ cap: string().min(1),
6778
+ kind: string().min(1).optional()
6779
+ });
6780
+ /** The links a kind declares, read from the meta of its body fields. */
6781
+ function linksOfKind(kind) {
6782
+ const schema = kind.schema;
6783
+ if (!(schema instanceof ZodObject)) return [];
6784
+ const links = [];
6785
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6786
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6787
+ if (to !== void 0) links.push({
6788
+ field,
6789
+ to
6790
+ });
6791
+ }
6792
+ return links;
6831
6793
  }
6832
- /** Every scope, in the order the guard and the docs list them. */
6833
- var SCOPED_SETTINGS_SCOPES = [
6834
- "cluster",
6835
- "device-defaults",
6836
- "node"
6837
- ];
6838
6794
  /**
6839
6795
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6840
6796
  *
@@ -6969,6 +6925,643 @@ function parseSecretRef(ref) {
6969
6925
  fieldPath
6970
6926
  };
6971
6927
  }
6928
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6929
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6930
+ var RECORD_DATABASES = ["settings", "events"];
6931
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6932
+ var RECORD_CLASSES = [
6933
+ "config",
6934
+ "ledger",
6935
+ "audit",
6936
+ "mirror",
6937
+ "ephemeral"
6938
+ ];
6939
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6940
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6941
+ var RECORD_BATCH_MAX = 1e3;
6942
+ var RECORD_QUERY_MAX = 1e3;
6943
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6944
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6945
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6946
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6947
+ /**
6948
+ * Secret fields of a record, addressed the way a Zod schema declares them
6949
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6950
+ * (`auth.accessToken`, `headers[].value`).
6951
+ *
6952
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6953
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6954
+ * key releases exactly that key's secret.
6955
+ *
6956
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6957
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6958
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6959
+ * leaf names its element: `headers[X-Api].value`.
6960
+ *
6961
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6962
+ */
6963
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6964
+ function parseSecretPath(path) {
6965
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6966
+ return path.split(".").map((raw) => {
6967
+ const each = raw.endsWith("[]");
6968
+ const map = raw.endsWith("{}");
6969
+ const key = each || map ? raw.slice(0, -2) : raw;
6970
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6971
+ return {
6972
+ key,
6973
+ each,
6974
+ map
6975
+ };
6976
+ });
6977
+ }
6978
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6979
+ function secretArrayPrefixes(path) {
6980
+ const segments = parseSecretPath(path);
6981
+ const prefixes = [];
6982
+ const walked = [];
6983
+ for (const segment of segments) {
6984
+ walked.push(segment.key);
6985
+ if (segment.each) prefixes.push(walked.join("."));
6986
+ }
6987
+ return prefixes;
6988
+ }
6989
+ function isRecord$6(value) {
6990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6991
+ }
6992
+ function elementId(element, idKey, declared, prefix) {
6993
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6994
+ 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`);
6995
+ return id;
6996
+ }
6997
+ /**
6998
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6999
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7000
+ * result is a new body, `data` is untouched.
7001
+ */
7002
+ var REMOVE_LEAF = Symbol("remove-leaf");
7003
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7004
+ if (!isRecord$6(node)) return node;
7005
+ const segment = segments[index];
7006
+ if (segment === void 0) return node;
7007
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7008
+ const child = node[segment.key];
7009
+ const keys = [...walkedKeys, segment.key];
7010
+ const last = index === segments.length - 1;
7011
+ if (segment.each) {
7012
+ if (!Array.isArray(child)) return node;
7013
+ const prefix = keys.join(".");
7014
+ const idKey = arrayKeys[prefix];
7015
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7016
+ const mapped = child.map((element) => {
7017
+ const id = elementId(element, idKey, declared, prefix);
7018
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7019
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7020
+ });
7021
+ return {
7022
+ ...node,
7023
+ [segment.key]: mapped
7024
+ };
7025
+ }
7026
+ if (segment.map) {
7027
+ if (!isRecord$6(child)) return node;
7028
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7029
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7030
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7031
+ return [mapKey, visit({
7032
+ declared,
7033
+ concrete,
7034
+ value
7035
+ })];
7036
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7037
+ return {
7038
+ ...node,
7039
+ [segment.key]: Object.fromEntries(kept)
7040
+ };
7041
+ }
7042
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7043
+ if (last) {
7044
+ const replacement = visit({
7045
+ declared,
7046
+ concrete,
7047
+ value: child
7048
+ });
7049
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7050
+ return {
7051
+ ...node,
7052
+ [segment.key]: replacement
7053
+ };
7054
+ }
7055
+ return {
7056
+ ...node,
7057
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7058
+ };
7059
+ }
7060
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7061
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7062
+ let current = data;
7063
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7064
+ return current;
7065
+ }
7066
+ /**
7067
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7068
+ * record's refs never collide with the refs a legacy collection of the same name
7069
+ * already holds during an adoption.
7070
+ */
7071
+ function recordSecretCollection(kind) {
7072
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7073
+ }
7074
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7075
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7076
+ return buildSecretRef({
7077
+ owner,
7078
+ scope: {
7079
+ kind: "row",
7080
+ collection: recordSecretCollection(kind),
7081
+ rowId
7082
+ },
7083
+ fieldPath: concretePath
7084
+ });
7085
+ }
7086
+ /**
7087
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7088
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7089
+ * token. The form hands it to the secret field, which reveals the value by ref
7090
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7091
+ * stored secret (the records door reads a view as KEEP).
7092
+ *
7093
+ * ONE implementation for the entries service and for every addon that serves
7094
+ * its own instances (`RecordIntegrationInstances`).
7095
+ */
7096
+ function isRecord$5(value) {
7097
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7098
+ }
7099
+ function secretViewsOf(owner, kind, id, decl, data) {
7100
+ if (decl.secretPaths.length === 0) return data;
7101
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7102
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7103
+ return {
7104
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7105
+ v: 1,
7106
+ set: true
7107
+ };
7108
+ });
7109
+ return isRecord$5(shown) ? shown : data;
7110
+ }
7111
+ /** The most instances one addon lists (an integrations page, not a table). */
7112
+ var INSTANCES_LIST_MAX = 1e3;
7113
+ /**
7114
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7115
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7116
+ */
7117
+ function isInstanceEnabled(body) {
7118
+ return body.enabled !== false;
7119
+ }
7120
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7121
+ var SWITCH_KEY = "enabled";
7122
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7123
+ function topLevelSecretKeys(paths) {
7124
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7125
+ }
7126
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7127
+ function secretMapKeys(paths) {
7128
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7129
+ }
7130
+ /**
7131
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7132
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7133
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7134
+ */
7135
+ function secretMapPatch(value) {
7136
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7137
+ const out = {};
7138
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7139
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7140
+ return Object.keys(out).length > 0 ? out : null;
7141
+ }
7142
+ var RecordIntegrationInstances = class {
7143
+ records;
7144
+ kind;
7145
+ hooks;
7146
+ handle;
7147
+ secretKeys;
7148
+ secretMaps;
7149
+ nameField;
7150
+ switchListeners = /* @__PURE__ */ new Set();
7151
+ constructor(records, kind, hooks) {
7152
+ this.records = records;
7153
+ this.kind = kind;
7154
+ this.hooks = hooks;
7155
+ this.handle = records.kind(kind);
7156
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7157
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7158
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7159
+ }
7160
+ /**
7161
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7162
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7163
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7164
+ */
7165
+ async readResolved(id) {
7166
+ try {
7167
+ const record = await this.handle.getResolved(id);
7168
+ return record === null ? null : {
7169
+ id,
7170
+ body: record.data,
7171
+ enabled: isInstanceEnabled(record.data),
7172
+ secrets: "resolved"
7173
+ };
7174
+ } catch (err) {
7175
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7176
+ const stored = await this.handle.get(id);
7177
+ if (stored === null) return null;
7178
+ return {
7179
+ id,
7180
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7181
+ enabled: isInstanceEnabled(stored.data),
7182
+ secrets: "unavailable"
7183
+ };
7184
+ }
7185
+ }
7186
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7187
+ async getResolved(id) {
7188
+ return (await this.readResolved(id))?.body ?? null;
7189
+ }
7190
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7191
+ async listResolved() {
7192
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7193
+ const out = [];
7194
+ for (const record of page.records) {
7195
+ const read = await this.readResolved(record.id);
7196
+ if (read !== null) out.push(read);
7197
+ }
7198
+ return out;
7199
+ }
7200
+ viewOf(record) {
7201
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7202
+ const rawName = record.data[this.nameField];
7203
+ const kind = this.hooks.kindOf?.(record.data);
7204
+ const health = this.hooks.health?.(record.data, record.id);
7205
+ return {
7206
+ id: record.id,
7207
+ name: typeof rawName === "string" ? rawName : record.id,
7208
+ configured: this.hooks.configured(record.data),
7209
+ enabled: isInstanceEnabled(record.data),
7210
+ formValues: shown,
7211
+ ...kind !== void 0 ? { kind } : {},
7212
+ ...health?.status !== void 0 ? { status: health.status } : {},
7213
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7214
+ };
7215
+ }
7216
+ describe = async () => {
7217
+ const declared = linksOfKind(this.kind);
7218
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7219
+ kind: this.kind.name,
7220
+ field: link.field,
7221
+ to: link.to
7222
+ })) };
7223
+ return {
7224
+ ...this.hooks.description,
7225
+ ...links,
7226
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7227
+ };
7228
+ };
7229
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7230
+ listInstances = async () => {
7231
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7232
+ };
7233
+ getInstance = async ({ id }) => {
7234
+ const record = await this.handle.get(id);
7235
+ return record === null ? null : this.viewOf(record);
7236
+ };
7237
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7238
+ createInstance = async ({ id, name, kind, values }) => {
7239
+ const minted = id ?? this.hooks.mintId?.({
7240
+ name,
7241
+ ...kind !== void 0 ? { kind } : {}
7242
+ });
7243
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7244
+ await this.handle.put({
7245
+ id: minted,
7246
+ data: this.hooks.initialBody(name, kind)
7247
+ }, { ifRev: 0 });
7248
+ const patch = this.patchOf(values ?? {});
7249
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7250
+ await this.hooks.onChanged?.(minted, "created");
7251
+ return { id: minted };
7252
+ };
7253
+ updateInstance = async ({ id, name, values }) => {
7254
+ const patch = this.patchOf(values);
7255
+ if (name !== void 0) patch[this.nameField] = name;
7256
+ await this.handle.patch(id, patch);
7257
+ await this.hooks.onChanged?.(id, "updated");
7258
+ return { ok: true };
7259
+ };
7260
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7261
+ patchOf(values) {
7262
+ const patch = {};
7263
+ for (const [key, value] of Object.entries(values)) {
7264
+ if (value === void 0) continue;
7265
+ if (key === "enabled") continue;
7266
+ if (this.secretMaps.has(key)) {
7267
+ const entries = secretMapPatch(value);
7268
+ if (entries !== null) patch[key] = entries;
7269
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7270
+ else if (isSecretClear(value)) patch[key] = null;
7271
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7272
+ }
7273
+ return patch;
7274
+ }
7275
+ /**
7276
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7277
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7278
+ * addon reconciles from the record, whichever way it flipped.
7279
+ */
7280
+ onSwitched(listener) {
7281
+ this.switchListeners.add(listener);
7282
+ }
7283
+ /**
7284
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7285
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7286
+ * never configured) gets its record from `initialBody` before the switch is written.
7287
+ */
7288
+ setInstanceEnabled = async ({ id, enabled }) => {
7289
+ if (await this.handle.get(id) === null) await this.handle.put({
7290
+ id,
7291
+ data: this.hooks.initialBody(id)
7292
+ }, { ifRev: 0 });
7293
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7294
+ await this.hooks.onChanged?.(id, "enabled");
7295
+ for (const listener of this.switchListeners) await listener(id, enabled);
7296
+ return { ok: true };
7297
+ };
7298
+ /** The row and its keychain refs go together (the records door). */
7299
+ deleteInstance = async ({ id }) => {
7300
+ await this.handle.delete(id);
7301
+ await this.hooks.onChanged?.(id, "deleted");
7302
+ return { ok: true };
7303
+ };
7304
+ testInstance = async (input) => {
7305
+ if (this.hooks.test === void 0) return {
7306
+ success: false,
7307
+ status: "unsupported",
7308
+ error: "This integration declares no connection test"
7309
+ };
7310
+ return this.hooks.test(input);
7311
+ };
7312
+ /** The flat provider object to hand to `registerProvider`. */
7313
+ toProvider() {
7314
+ return {
7315
+ describe: this.describe,
7316
+ instanceFormSchema: this.instanceFormSchema,
7317
+ listInstances: this.listInstances,
7318
+ getInstance: this.getInstance,
7319
+ createInstance: this.createInstance,
7320
+ updateInstance: this.updateInstance,
7321
+ setInstanceEnabled: this.setInstanceEnabled,
7322
+ deleteInstance: this.deleteInstance,
7323
+ testInstance: this.testInstance
7324
+ };
7325
+ }
7326
+ };
7327
+ /**
7328
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7329
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7330
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7331
+ *
7332
+ * For every registry row of the addon that is OFF:
7333
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7334
+ * (a default integration that never had settings, Reolink's among them);
7335
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7336
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7337
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7338
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7339
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7340
+ *
7341
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7342
+ * which is also why `integrations.list` still answers the stored column at that point.
7343
+ */
7344
+ function registrySwitchToBodyId(addonId, date) {
7345
+ return `${addonId}/${date}-registry-switch-to-body`;
7346
+ }
7347
+ async function moveRegistrySwitchToBody(ports, spec) {
7348
+ const rows = await ports.listIntegrations(spec.addonId);
7349
+ let created = 0;
7350
+ let switched = 0;
7351
+ let kept = 0;
7352
+ for (const row of rows) {
7353
+ if (row.enabled) continue;
7354
+ const body = await ports.readBody(row.id);
7355
+ if (body === null) {
7356
+ if (await ports.createRecord(row.id, {
7357
+ ...spec.initialBody(row.name),
7358
+ ["enabled"]: false
7359
+ }) === "created") created += 1;
7360
+ else kept += 1;
7361
+ continue;
7362
+ }
7363
+ if ("enabled" in body) {
7364
+ kept += 1;
7365
+ continue;
7366
+ }
7367
+ await ports.switchOff(row.id);
7368
+ switched += 1;
7369
+ }
7370
+ const summary = {
7371
+ integrations: rows.length,
7372
+ off: rows.filter((r) => !r.enabled).length,
7373
+ created,
7374
+ switched,
7375
+ kept
7376
+ };
7377
+ return created === 0 && switched === 0 ? {
7378
+ outcome: "already-done",
7379
+ summary
7380
+ } : {
7381
+ outcome: "done",
7382
+ summary
7383
+ };
7384
+ }
7385
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7386
+ function registrySwitchToBodyMigration(spec) {
7387
+ return {
7388
+ meta: {
7389
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7390
+ owner: spec.addonId,
7391
+ level: "addon-state",
7392
+ seq: spec.seq,
7393
+ dependsOn: [],
7394
+ store: "settings",
7395
+ scope: "cluster",
7396
+ onFailure: "block-owner",
7397
+ bodyKind: "procedure",
7398
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7399
+ fixtureMark: "enabled"
7400
+ },
7401
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7402
+ addonId: spec.addonId,
7403
+ initialBody: spec.initialBody
7404
+ })
7405
+ };
7406
+ }
7407
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7408
+ function registrySwitchPortsOver(deps) {
7409
+ const handle = deps.records.kind({
7410
+ name: deps.kind.name,
7411
+ declaration: deps.kind.declaration,
7412
+ schema: record(string(), unknown())
7413
+ });
7414
+ return {
7415
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7416
+ id: i.id,
7417
+ name: i.name,
7418
+ enabled: i.enabled !== false
7419
+ })),
7420
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7421
+ createRecord: async (id, body) => {
7422
+ if (await handle.get(id) !== null) return "exists";
7423
+ await handle.put({
7424
+ id,
7425
+ data: body
7426
+ }, { ifRev: 0 });
7427
+ return "created";
7428
+ },
7429
+ switchOff: async (id) => {
7430
+ await handle.patch(id, { [SWITCH_KEY]: false });
7431
+ }
7432
+ };
7433
+ }
7434
+ /**
7435
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7436
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7437
+ * validated value round-trips on every read/write — the schema is the
7438
+ * single source of truth for what is persisted, so no hand-listed field
7439
+ * set can drop a key on save.
7440
+ */
7441
+ function createDurableState(deps) {
7442
+ const get = async () => {
7443
+ const raw = (await deps.read())[deps.key];
7444
+ if (raw === void 0) return deps.fallback;
7445
+ const parsed = deps.schema.safeParse(raw);
7446
+ if (!parsed.success) {
7447
+ deps.onParseError?.(deps.key, parsed.error);
7448
+ return deps.fallback;
7449
+ }
7450
+ return parsed.data;
7451
+ };
7452
+ const set = async (next) => {
7453
+ const validated = deps.schema.parse(next);
7454
+ await deps.write({ [deps.key]: validated });
7455
+ };
7456
+ const update = async (fn) => {
7457
+ await set(fn(await get()));
7458
+ };
7459
+ return {
7460
+ get,
7461
+ set,
7462
+ update
7463
+ };
7464
+ }
7465
+ /**
7466
+ * Per-node scoping for the shared addon-settings blob.
7467
+ *
7468
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7469
+ * hub-routed — the hub instance answers for every node), so fields whose
7470
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7471
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7472
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7473
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7474
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7475
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7476
+ *
7477
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7478
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7479
+ * schema and routes reads/writes through these helpers.
7480
+ *
7481
+ * ## No bare-key fallback — deliberate
7482
+ *
7483
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7484
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7485
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7486
+ * the store is invisible to every node, hub included, so one node's
7487
+ * selection can never leak onto another. (This generalizes the
7488
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7489
+ * arbitrary set of per-node field keys.)
7490
+ *
7491
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7492
+ * LEAF module: import it via its deep path, never from the root barrel.
7493
+ */
7494
+ /**
7495
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7496
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7497
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7498
+ * `undefined` / `null` / empty falls back to `'hub'`.
7499
+ */
7500
+ function normalizeNodeId(raw) {
7501
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7502
+ const slashIdx = raw.indexOf("/");
7503
+ if (slashIdx < 0) return raw;
7504
+ const bare = raw.slice(0, slashIdx);
7505
+ return bare === "" ? "hub" : bare;
7506
+ }
7507
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7508
+ function nodeScopedKey(base, nodeId) {
7509
+ return `${base}@${normalizeNodeId(nodeId)}`;
7510
+ }
7511
+ /**
7512
+ * Read a node's value for a per-node field from the raw shared store:
7513
+ * the node-scoped key when present, otherwise `undefined`.
7514
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7515
+ * schema `default` win on `undefined`.
7516
+ */
7517
+ function readNodeValue(store, base, nodeId) {
7518
+ return store[nodeScopedKey(base, nodeId)];
7519
+ }
7520
+ /**
7521
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7522
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7523
+ * the write path so a save for one node never clobbers another node's value
7524
+ * (and the bare key is never written). Returns a new object — the input
7525
+ * patch is not mutated.
7526
+ */
7527
+ function scopePatch(patch, perNodeKeys, nodeId) {
7528
+ const out = {};
7529
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7530
+ return out;
7531
+ }
7532
+ /**
7533
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7534
+ * UI schema (whose field keys are bare) hydrates from that node's own
7535
+ * values:
7536
+ *
7537
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7538
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7539
+ * legacy key must never hydrate any node — no bare fallback).
7540
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7541
+ * each bare perNode key; when the node has no scoped key the bare key is
7542
+ * left ABSENT so the field's schema `default` wins.
7543
+ *
7544
+ * Returns a new object — the input store is not mutated.
7545
+ */
7546
+ function projectStore(store, perNodeKeys, nodeId) {
7547
+ const out = {};
7548
+ for (const [key, value] of Object.entries(store)) {
7549
+ if (key.includes("@")) continue;
7550
+ if (perNodeKeys.has(key)) continue;
7551
+ out[key] = value;
7552
+ }
7553
+ for (const base of perNodeKeys) {
7554
+ const value = readNodeValue(store, base, nodeId);
7555
+ if (value !== void 0) out[base] = value;
7556
+ }
7557
+ return out;
7558
+ }
7559
+ /** Every scope, in the order the guard and the docs list them. */
7560
+ var SCOPED_SETTINGS_SCOPES = [
7561
+ "cluster",
7562
+ "device-defaults",
7563
+ "node"
7564
+ ];
6972
7565
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6973
7566
  var KeychainWriteRefusedError = class extends Error {
6974
7567
  fieldPath;
@@ -6979,7 +7572,7 @@ var KeychainWriteRefusedError = class extends Error {
6979
7572
  }
6980
7573
  };
6981
7574
  var KEEP = { kind: "keep" };
6982
- function isRecord$6(value) {
7575
+ function isRecord$4(value) {
6983
7576
  return typeof value === "object" && value !== null && !Array.isArray(value);
6984
7577
  }
6985
7578
  function defaultMintId() {
@@ -6992,7 +7585,7 @@ function collectSecretMarkerRefs(value, out = []) {
6992
7585
  return out;
6993
7586
  }
6994
7587
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6995
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7588
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6996
7589
  return out;
6997
7590
  }
6998
7591
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7047,7 +7640,7 @@ function rowId(row, idKey) {
7047
7640
  return null;
7048
7641
  }
7049
7642
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7050
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7643
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7051
7644
  if (!Array.isArray(incoming)) {
7052
7645
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7053
7646
  return {
@@ -7063,7 +7656,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7063
7656
  const kept = /* @__PURE__ */ new Set();
7064
7657
  const rows = [];
7065
7658
  for (const row of incoming) {
7066
- if (!isRecord$6(row)) {
7659
+ if (!isRecord$4(row)) {
7067
7660
  rows.push(row);
7068
7661
  continue;
7069
7662
  }
@@ -7088,7 +7681,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7088
7681
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7089
7682
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7090
7683
  case "object": {
7091
- if (!isRecord$6(incoming)) {
7684
+ if (!isRecord$4(incoming)) {
7092
7685
  if (incoming === void 0) return KEEP;
7093
7686
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7094
7687
  return {
@@ -7096,7 +7689,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7096
7689
  value: incoming
7097
7690
  };
7098
7691
  }
7099
- const storedObj = isRecord$6(stored) ? stored : {};
7692
+ const storedObj = isRecord$4(stored) ? stored : {};
7100
7693
  return {
7101
7694
  kind: "value",
7102
7695
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7219,7 +7812,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7219
7812
  value: items
7220
7813
  };
7221
7814
  }
7222
- if (isRecord$6(v)) {
7815
+ if (isRecord$4(v)) {
7223
7816
  const out = {};
7224
7817
  for (const [k, child] of Object.entries(v)) {
7225
7818
  const s = substitute(child);
@@ -7251,7 +7844,7 @@ var SecretOverwriteRefusedError = class extends Error {
7251
7844
  this.name = "SecretOverwriteRefusedError";
7252
7845
  }
7253
7846
  };
7254
- function isRecord$5(value) {
7847
+ function isRecord$3(value) {
7255
7848
  return typeof value === "object" && value !== null && !Array.isArray(value);
7256
7849
  }
7257
7850
  function resolvedValue(pass, marker) {
@@ -7280,7 +7873,7 @@ function inArray(pass, incoming, stored) {
7280
7873
  return incoming.map((item, index) => {
7281
7874
  const twin = stored[index];
7282
7875
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7283
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7876
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7284
7877
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7285
7878
  return item;
7286
7879
  });
@@ -7291,7 +7884,7 @@ function inArrayRow(pass, incoming, stored) {
7291
7884
  const twin = stored[key];
7292
7885
  if (isSecretMarker(twin)) {
7293
7886
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7294
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7887
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7295
7888
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7296
7889
  }
7297
7890
  return out;
@@ -7299,7 +7892,7 @@ function inArrayRow(pass, incoming, stored) {
7299
7892
  async function walk(pass, incoming, stored) {
7300
7893
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7301
7894
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7302
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7895
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7303
7896
  const out = { ...incoming };
7304
7897
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7305
7898
  return out;
@@ -7330,7 +7923,7 @@ async function restoreUnchangedSecrets(input) {
7330
7923
  function isJsonEqual(a, b) {
7331
7924
  if (Object.is(a, b)) return true;
7332
7925
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7333
- if (isRecord$5(a) && isRecord$5(b)) {
7926
+ if (isRecord$3(a) && isRecord$3(b)) {
7334
7927
  const keys = Object.keys(a);
7335
7928
  if (keys.length !== Object.keys(b).length) return false;
7336
7929
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7354,7 +7947,7 @@ function markerKeysOf(blob, owner) {
7354
7947
  }
7355
7948
  function nodeFromStored(value, owner) {
7356
7949
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7357
- if (!isRecord$5(value)) return null;
7950
+ if (!isRecord$3(value)) return null;
7358
7951
  const children = /* @__PURE__ */ new Map();
7359
7952
  for (const [key, child] of Object.entries(value)) {
7360
7953
  const node = nodeFromStored(child, owner);
@@ -7851,13 +8444,48 @@ var BaseAddon = class {
7851
8444
  if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7852
8445
  return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7853
8446
  }
7854
- async runBound(migrations, options) {
8447
+ /**
8448
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8449
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8450
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8451
+ * on every declare).
8452
+ */
8453
+ declareRegistrySwitch(spec) {
8454
+ this.registrySwitchSpec = spec;
8455
+ }
8456
+ registrySwitchSpec = null;
8457
+ registrySwitchBound() {
8458
+ const spec = this.registrySwitchSpec;
8459
+ if (spec === null) return [];
8460
+ const api = this.ctx.migrationApi;
8461
+ if (api === void 0) {
8462
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8463
+ return [];
8464
+ }
8465
+ return migrationSet([registrySwitchToBodyMigration({
8466
+ addonId: this.ctx.id,
8467
+ date: "2026-11-06",
8468
+ seq: 1e3,
8469
+ initialBody: spec.initialBody
8470
+ })], (a) => registrySwitchPortsOver({
8471
+ api: integrationRowsApiOver(a),
8472
+ records: switchRecordsOverMigrationApi(a),
8473
+ kind: spec.kind
8474
+ })).bind(api);
8475
+ }
8476
+ async runBound(declared, options) {
8477
+ const added = this.registrySwitchBound();
8478
+ const migrations = [...declared, ...added];
8479
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8480
+ ...options,
8481
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8482
+ };
7855
8483
  const api = this.ctx.api.migrations;
7856
8484
  const report = await runAddonMigrations({
7857
8485
  declareOwner: (input) => api.declareOwner.mutate(input),
7858
8486
  startMigration: (input) => api.startMigration.mutate(input),
7859
8487
  finishMigration: (input) => api.finishMigration.mutate(input)
7860
- }, migrations, this.ctx.logger, options);
8488
+ }, migrations, this.ctx.logger, phased);
7861
8489
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7862
8490
  return report;
7863
8491
  }
@@ -8930,228 +9558,6 @@ function normalizeAddonInitResult(result) {
8930
9558
  if (Array.isArray(result)) return { providers: result };
8931
9559
  return result;
8932
9560
  }
8933
- var PREFIX = "records/";
8934
- /** The base of every records failure. `detail` is the human part of the message. */
8935
- var RecordsError = class extends Error {
8936
- code;
8937
- detail;
8938
- constructor(code, detail) {
8939
- super(`${PREFIX}${code}: ${detail}`);
8940
- this.name = "RecordsError";
8941
- this.code = code;
8942
- this.detail = detail;
8943
- }
8944
- };
8945
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8946
- var RevConflictError = class extends RecordsError {
8947
- constructor(detail) {
8948
- super("rev-conflict", detail);
8949
- this.name = "RevConflictError";
8950
- }
8951
- };
8952
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8953
- var RecordSecretUnavailableError = class extends RecordsError {
8954
- constructor(detail) {
8955
- super("secret-unavailable", detail);
8956
- this.name = "RecordSecretUnavailableError";
8957
- }
8958
- };
8959
- var InvalidRecordError = class extends RecordsError {
8960
- constructor(detail) {
8961
- super("invalid-record", detail);
8962
- this.name = "InvalidRecordError";
8963
- }
8964
- };
8965
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8966
- var DeclarationRefusedError = class extends RecordsError {
8967
- constructor(detail) {
8968
- super("declaration-refused", detail);
8969
- this.name = "DeclarationRefusedError";
8970
- }
8971
- };
8972
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8973
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8974
- var RECORD_DATABASES = ["settings", "events"];
8975
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8976
- var RECORD_CLASSES = [
8977
- "config",
8978
- "ledger",
8979
- "audit",
8980
- "mirror",
8981
- "ephemeral"
8982
- ];
8983
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8984
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8985
- var RECORD_BATCH_MAX = 1e3;
8986
- var RECORD_QUERY_MAX = 1e3;
8987
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8988
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8989
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8990
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8991
- /**
8992
- * Secret fields of a record, addressed the way a Zod schema declares them
8993
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8994
- * (`auth.accessToken`, `headers[].value`).
8995
- *
8996
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8997
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8998
- * key releases exactly that key's secret.
8999
- *
9000
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
9001
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
9002
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
9003
- * leaf names its element: `headers[X-Api].value`.
9004
- *
9005
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
9006
- */
9007
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
9008
- function parseSecretPath(path) {
9009
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
9010
- return path.split(".").map((raw) => {
9011
- const each = raw.endsWith("[]");
9012
- const map = raw.endsWith("{}");
9013
- const key = each || map ? raw.slice(0, -2) : raw;
9014
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
9015
- return {
9016
- key,
9017
- each,
9018
- map
9019
- };
9020
- });
9021
- }
9022
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
9023
- function secretArrayPrefixes(path) {
9024
- const segments = parseSecretPath(path);
9025
- const prefixes = [];
9026
- const walked = [];
9027
- for (const segment of segments) {
9028
- walked.push(segment.key);
9029
- if (segment.each) prefixes.push(walked.join("."));
9030
- }
9031
- return prefixes;
9032
- }
9033
- function isRecord$4(value) {
9034
- return typeof value === "object" && value !== null && !Array.isArray(value);
9035
- }
9036
- function elementId(element, idKey, declared, prefix) {
9037
- const id = isRecord$4(element) ? element[idKey] : void 0;
9038
- 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`);
9039
- return id;
9040
- }
9041
- /**
9042
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9043
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9044
- * result is a new body, `data` is untouched.
9045
- */
9046
- var REMOVE_LEAF = Symbol("remove-leaf");
9047
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9048
- if (!isRecord$4(node)) return node;
9049
- const segment = segments[index];
9050
- if (segment === void 0) return node;
9051
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9052
- const child = node[segment.key];
9053
- const keys = [...walkedKeys, segment.key];
9054
- const last = index === segments.length - 1;
9055
- if (segment.each) {
9056
- if (!Array.isArray(child)) return node;
9057
- const prefix = keys.join(".");
9058
- const idKey = arrayKeys[prefix];
9059
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9060
- const mapped = child.map((element) => {
9061
- const id = elementId(element, idKey, declared, prefix);
9062
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9063
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9064
- });
9065
- return {
9066
- ...node,
9067
- [segment.key]: mapped
9068
- };
9069
- }
9070
- if (segment.map) {
9071
- if (!isRecord$4(child)) return node;
9072
- const kept = Object.entries(child).map(([mapKey, value]) => {
9073
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9074
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9075
- return [mapKey, visit({
9076
- declared,
9077
- concrete,
9078
- value
9079
- })];
9080
- }).filter(([, value]) => value !== REMOVE_LEAF);
9081
- return {
9082
- ...node,
9083
- [segment.key]: Object.fromEntries(kept)
9084
- };
9085
- }
9086
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9087
- if (last) {
9088
- const replacement = visit({
9089
- declared,
9090
- concrete,
9091
- value: child
9092
- });
9093
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9094
- return {
9095
- ...node,
9096
- [segment.key]: replacement
9097
- };
9098
- }
9099
- return {
9100
- ...node,
9101
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9102
- };
9103
- }
9104
- /** Replace/remove every present secret leaf; returns a NEW body. */
9105
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9106
- let current = data;
9107
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9108
- return current;
9109
- }
9110
- /**
9111
- * The keychain collection name a kind's secrets live under. Prefixed so a
9112
- * record's refs never collide with the refs a legacy collection of the same name
9113
- * already holds during an adoption.
9114
- */
9115
- function recordSecretCollection(kind) {
9116
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9117
- }
9118
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9119
- function recordSecretRef(owner, kind, rowId, concretePath) {
9120
- return buildSecretRef({
9121
- owner,
9122
- scope: {
9123
- kind: "row",
9124
- collection: recordSecretCollection(kind),
9125
- rowId
9126
- },
9127
- fieldPath: concretePath
9128
- });
9129
- }
9130
- /**
9131
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9132
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9133
- * token. The form hands it to the secret field, which reveals the value by ref
9134
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9135
- * stored secret (the records door reads a view as KEEP).
9136
- *
9137
- * ONE implementation for the entries service and for every addon that serves
9138
- * its own instances (`RecordIntegrationInstances`).
9139
- */
9140
- function isRecord$3(value) {
9141
- return typeof value === "object" && value !== null && !Array.isArray(value);
9142
- }
9143
- function secretViewsOf(owner, kind, id, decl, data) {
9144
- if (decl.secretPaths.length === 0) return data;
9145
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9146
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9147
- return {
9148
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9149
- v: 1,
9150
- set: true
9151
- };
9152
- });
9153
- return isRecord$3(shown) ? shown : data;
9154
- }
9155
9561
  /**
9156
9562
  * The share-view scope kinds a share-link token can carry. The hub mints
9157
9563
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9405,6 +9811,7 @@ function defineRecordKinds(specs) {
9405
9811
  function entryBody(shape) {
9406
9812
  return object({
9407
9813
  name: string().min(1),
9814
+ enabled: boolean().optional(),
9408
9815
  ...shape
9409
9816
  });
9410
9817
  }
@@ -11244,6 +11651,10 @@ Object.freeze({
11244
11651
  "all",
11245
11652
  "one"
11246
11653
  ]
11654
+ },
11655
+ {
11656
+ "path": "positionUpdatedAt",
11657
+ "valueType": "number"
11247
11658
  }
11248
11659
  ],
11249
11660
  "meter": [{
@@ -11498,22 +11909,6 @@ Object.freeze({
11498
11909
  "path": "pumpRunning",
11499
11910
  "valueType": "boolean"
11500
11911
  },
11501
- {
11502
- "path": "lastDrink",
11503
- "valueType": "number"
11504
- },
11505
- {
11506
- "path": "currentHourDrink",
11507
- "valueType": "number"
11508
- },
11509
- {
11510
- "path": "last24hDrink",
11511
- "valueType": "number"
11512
- },
11513
- {
11514
- "path": "todayDrink",
11515
- "valueType": "number"
11516
- },
11517
11912
  {
11518
11913
  "path": "error",
11519
11914
  "valueType": "string"
@@ -12079,6 +12474,60 @@ Object.freeze({
12079
12474
  }
12080
12475
  ]
12081
12476
  });
12477
+ Object.freeze({
12478
+ "actions": { "run": 363e4 },
12479
+ "audio-analyzer": { "classify": 3e4 },
12480
+ "custom-model-registry": { "importModelBundle": 18e5 },
12481
+ "database-snapshot": { "writeSnapshot": 18e5 },
12482
+ "device-manager": {
12483
+ "migrateDevice": 72e4,
12484
+ "runDiscoverySweep": 12e4
12485
+ },
12486
+ "device-provider": { "reloadDevice": 18e4 },
12487
+ "llm": {
12488
+ "generate": 6e5,
12489
+ "generateVision": 6e5,
12490
+ "testProfile": 6e5
12491
+ },
12492
+ "llm-runtime": {
12493
+ "complete": 6e5,
12494
+ "completeApple": 6e5,
12495
+ "ensureStarted": 6e5,
12496
+ "installModel": 36e5
12497
+ },
12498
+ "local-network": { "scanNetwork": 9e4 },
12499
+ "model-convert": { "convert": 6e5 },
12500
+ "pipeline-analytics": {
12501
+ "addRetrainFrameFromRecording": 6e4,
12502
+ "offerRetrainArchive": 12e4,
12503
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12504
+ "resolveRetrainTrainingCorpus": 6e4,
12505
+ "writeRetrainArchive": 36e5
12506
+ },
12507
+ "server-management": { "applyServerUpdate": 96e4 },
12508
+ "terminal-session": { "pullOutput": 15e3 },
12509
+ "training": {
12510
+ "canaryResult": 12e4,
12511
+ "cancelJob": 12e4,
12512
+ "planJob": 6e4,
12513
+ "registerResult": 18e5,
12514
+ "rollbackCanary": 12e4,
12515
+ "startJob": 12e4,
12516
+ "startJobBatch": 12e4
12517
+ },
12518
+ "training-provider": {
12519
+ "cancelJob": 6e4,
12520
+ "cleanupJob": 3e5,
12521
+ "getJob": 6e4,
12522
+ "listJobEvents": 6e4,
12523
+ "listJobs": 12e4,
12524
+ "offerArtifact": 3e5,
12525
+ "readResult": 3e5,
12526
+ "submitJob": 18e5,
12527
+ "uploadDataset": 72e5,
12528
+ "validateCredentials": 3e4
12529
+ }
12530
+ });
12082
12531
  object({
12083
12532
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12084
12533
  params: record(string(), union([string(), number()])).optional()
@@ -12098,7 +12547,7 @@ function userError(code, params, englishFallback) {
12098
12547
  return new CamstackError(code, params, englishFallback);
12099
12548
  }
12100
12549
  //#endregion
12101
- //#region ../types/dist/composition-pOHbTzRB.mjs
12550
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12102
12551
  /**
12103
12552
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12104
12553
  *
@@ -12402,7 +12851,7 @@ var table = {
12402
12851
  },
12403
12852
  dwell: {
12404
12853
  minArgs: 3,
12405
- maxArgs: 3,
12854
+ maxArgs: 4,
12406
12855
  apply: () => {
12407
12856
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12408
12857
  }
@@ -13462,212 +13911,6 @@ var IntegrationInstanceRefSchema = object({
13462
13911
  ]),
13463
13912
  candidateStableId: string().optional()
13464
13913
  });
13465
- /**
13466
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13467
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13468
- *
13469
- * Every instance is one record of the addon's own kind, keyed by the
13470
- * `integrations` registry id. The records door does the secret work: a field the
13471
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13472
- * deleting the row deletes the secret, and one row's value is never another's.
13473
- *
13474
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13475
- * token or the view the form was given KEEP the stored secret;
13476
- * `{ $secretClear: true }` clears it; any other string replaces it.
13477
- */
13478
- /** The most instances one addon lists (an integrations page, not a table). */
13479
- var INSTANCES_LIST_MAX = 1e3;
13480
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13481
- function topLevelSecretKeys(paths) {
13482
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13483
- }
13484
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13485
- function secretMapKeys(paths) {
13486
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13487
- }
13488
- /**
13489
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13490
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13491
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13492
- */
13493
- function secretMapPatch(value) {
13494
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13495
- const out = {};
13496
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13497
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13498
- return Object.keys(out).length > 0 ? out : null;
13499
- }
13500
- /** Does the kind's body schema carry an `enabled` field? */
13501
- function declaresEnabled(kind) {
13502
- const json = toJSONSchema(kind.schema, {
13503
- unrepresentable: "any",
13504
- io: "input"
13505
- });
13506
- const properties = Reflect.get(json, "properties");
13507
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13508
- }
13509
- var RecordIntegrationInstances = class {
13510
- records;
13511
- kind;
13512
- hooks;
13513
- handle;
13514
- secretKeys;
13515
- secretMaps;
13516
- nameField;
13517
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13518
- registryOwnsEnabled;
13519
- constructor(records, kind, hooks) {
13520
- this.records = records;
13521
- this.kind = kind;
13522
- this.hooks = hooks;
13523
- this.handle = records.kind(kind);
13524
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13525
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13526
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13527
- this.registryOwnsEnabled = hooks.description.role === "devices";
13528
- 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"`);
13529
- }
13530
- /**
13531
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13532
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13533
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13534
- */
13535
- async readResolved(id) {
13536
- try {
13537
- const record = await this.handle.getResolved(id);
13538
- return record === null ? null : {
13539
- id,
13540
- body: record.data,
13541
- enabled: record.data.enabled !== false,
13542
- secrets: "resolved"
13543
- };
13544
- } catch (err) {
13545
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13546
- const stored = await this.handle.get(id);
13547
- if (stored === null) return null;
13548
- return {
13549
- id,
13550
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13551
- enabled: stored.data.enabled !== false,
13552
- secrets: "unavailable"
13553
- };
13554
- }
13555
- }
13556
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13557
- async getResolved(id) {
13558
- return (await this.readResolved(id))?.body ?? null;
13559
- }
13560
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13561
- async listResolved() {
13562
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13563
- const out = [];
13564
- for (const record of page.records) {
13565
- const read = await this.readResolved(record.id);
13566
- if (read !== null) out.push(read);
13567
- }
13568
- return out;
13569
- }
13570
- viewOf(record) {
13571
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13572
- const rawName = record.data[this.nameField];
13573
- const kind = this.hooks.kindOf?.(record.data);
13574
- const health = this.hooks.health?.(record.data, record.id);
13575
- return {
13576
- id: record.id,
13577
- name: typeof rawName === "string" ? rawName : record.id,
13578
- configured: this.hooks.configured(record.data),
13579
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13580
- formValues: shown,
13581
- ...kind !== void 0 ? { kind } : {},
13582
- ...health?.status !== void 0 ? { status: health.status } : {},
13583
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13584
- };
13585
- }
13586
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13587
- ...this.hooks.description,
13588
- mintsId: true
13589
- };
13590
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13591
- listInstances = async () => {
13592
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13593
- };
13594
- getInstance = async ({ id }) => {
13595
- const record = await this.handle.get(id);
13596
- return record === null ? null : this.viewOf(record);
13597
- };
13598
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13599
- createInstance = async ({ id, name, kind, values }) => {
13600
- const minted = id ?? this.hooks.mintId?.({
13601
- name,
13602
- ...kind !== void 0 ? { kind } : {}
13603
- });
13604
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13605
- await this.handle.put({
13606
- id: minted,
13607
- data: this.hooks.initialBody(name, kind)
13608
- }, { ifRev: 0 });
13609
- const patch = this.patchOf(values ?? {});
13610
- if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13611
- await this.hooks.onChanged?.(minted, "created");
13612
- return { id: minted };
13613
- };
13614
- updateInstance = async ({ id, name, values }) => {
13615
- const patch = this.patchOf(values);
13616
- if (name !== void 0) patch[this.nameField] = name;
13617
- await this.handle.patch(id, patch);
13618
- await this.hooks.onChanged?.(id, "updated");
13619
- return { ok: true };
13620
- };
13621
- /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13622
- patchOf(values) {
13623
- const patch = {};
13624
- for (const [key, value] of Object.entries(values)) {
13625
- if (value === void 0) continue;
13626
- if (this.secretMaps.has(key)) {
13627
- const entries = secretMapPatch(value);
13628
- if (entries !== null) patch[key] = entries;
13629
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13630
- else if (isSecretClear(value)) patch[key] = null;
13631
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13632
- }
13633
- return patch;
13634
- }
13635
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13636
- setInstanceEnabled = async ({ id, enabled }) => {
13637
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13638
- await this.handle.patch(id, { enabled });
13639
- await this.hooks.onChanged?.(id, "enabled");
13640
- return { ok: true };
13641
- };
13642
- /** The row and its keychain refs go together (the records door). */
13643
- deleteInstance = async ({ id }) => {
13644
- await this.handle.delete(id);
13645
- await this.hooks.onChanged?.(id, "deleted");
13646
- return { ok: true };
13647
- };
13648
- testInstance = async (input) => {
13649
- if (this.hooks.test === void 0) return {
13650
- success: false,
13651
- status: "unsupported",
13652
- error: "This integration declares no connection test"
13653
- };
13654
- return this.hooks.test(input);
13655
- };
13656
- /** The flat provider object to hand to `registerProvider`. */
13657
- toProvider() {
13658
- return {
13659
- describe: this.describe,
13660
- instanceFormSchema: this.instanceFormSchema,
13661
- listInstances: this.listInstances,
13662
- getInstance: this.getInstance,
13663
- createInstance: this.createInstance,
13664
- updateInstance: this.updateInstance,
13665
- setInstanceEnabled: this.setInstanceEnabled,
13666
- deleteInstance: this.deleteInstance,
13667
- testInstance: this.testInstance
13668
- };
13669
- }
13670
- };
13671
13914
  /** No part holds the id a call named. */
13672
13915
  var UnknownInstanceError = class extends Error {
13673
13916
  instanceId;
@@ -13706,10 +13949,14 @@ function composeInstanceKinds(parts, base) {
13706
13949
  kind: part.kind.id
13707
13950
  });
13708
13951
  return {
13709
- describe: async () => ({
13710
- ...base,
13711
- kinds: parts.map((part) => part.kind)
13712
- }),
13952
+ describe: async () => {
13953
+ const links = (await Promise.all(parts.map(async (part) => (await part.provider.describe()).links ?? []))).flat();
13954
+ return {
13955
+ ...base,
13956
+ kinds: parts.map((part) => part.kind),
13957
+ ...links.length > 0 ? { links } : {}
13958
+ };
13959
+ },
13713
13960
  instanceFormSchema: async ({ id, kind }) => {
13714
13961
  return (id === null ? byKind(kind) : await holderOf(id)).provider.instanceFormSchema({ id });
13715
13962
  },
@@ -19922,31 +20169,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19922
20169
  "pet-fountain": {
19923
20170
  scope: "device",
19924
20171
  noun: t("Pet fountain", "Fontana per animali"),
19925
- actions: [
19926
- {
19927
- id: "petFountain.pumpOn",
19928
- method: "setPump",
19929
- label: t("Pump on", "Pompa accesa"),
19930
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19931
- icon: "play",
19932
- args: { on: true }
19933
- },
19934
- {
19935
- id: "petFountain.pumpOff",
19936
- method: "setPump",
19937
- label: t("Pump off", "Pompa spenta"),
19938
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19939
- icon: "square",
19940
- args: { on: false }
19941
- },
19942
- {
19943
- id: "petFountain.resetDailyConsumption",
19944
- method: "resetDailyConsumption",
19945
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19946
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19947
- icon: "rotate-ccw"
19948
- }
19949
- ],
20172
+ actions: [{
20173
+ id: "petFountain.pumpOn",
20174
+ method: "setPump",
20175
+ label: t("Pump on", "Pompa accesa"),
20176
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20177
+ icon: "play",
20178
+ args: { on: true }
20179
+ }, {
20180
+ id: "petFountain.pumpOff",
20181
+ method: "setPump",
20182
+ label: t("Pump off", "Pompa spenta"),
20183
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20184
+ icon: "square",
20185
+ args: { on: false }
20186
+ }],
19950
20187
  state: [{
19951
20188
  kind: "boolean",
19952
20189
  field: "empty",
@@ -43840,8 +44077,15 @@ var ActionInputSchema = object({
43840
44077
  var ActionRunOriginSchema = object({
43841
44078
  /** The automation block whose step started it. */
43842
44079
  blockId: string().min(1).optional() });
43843
- /** `started` = the caller did not ask to wait. */
43844
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44080
+ /**
44081
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44082
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44083
+ */
44084
+ var ActionRunOutcomeSchema = union([
44085
+ AutomationRunOutcomeSchema,
44086
+ literal("started"),
44087
+ literal("timed-out")
44088
+ ]);
43845
44089
  var ActionRunResultSchema = object({
43846
44090
  runId: string().min(1),
43847
44091
  outcome: ActionRunOutcomeSchema,
@@ -44363,6 +44607,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44363
44607
  kind: "mutation",
44364
44608
  auth: "admin"
44365
44609
  });
44610
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44611
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44366
44612
  /**
44367
44613
  * actions — the ONE surface for runnable actions, for the UI and for
44368
44614
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44381,6 +44627,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44381
44627
  * An admin, and an in-process caller (an automation block), may run any action.
44382
44628
  * Every refusal is typed (`[not-linked] …`) and logged.
44383
44629
  *
44630
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44631
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44632
+ * `wait` steps alone add up to more is refused at create/update
44633
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44634
+ * waited call (an automation step) is never cut by the 60 s transport default.
44635
+ *
44384
44636
  * A second `run` of an action that is already running is REFUSED — traced and
44385
44637
  * logged — never queued.
44386
44638
  */
@@ -44407,7 +44659,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44407
44659
  role: "viewer",
44408
44660
  auth: "protected",
44409
44661
  kind: "mutation",
44410
- caller: "required"
44662
+ caller: "required",
44663
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44411
44664
  }), method(ActionIdInput, _void(), {
44412
44665
  kind: "mutation",
44413
44666
  auth: "admin"
@@ -48452,6 +48705,9 @@ var MediaPlayerStatusSchema = object({
48452
48705
  /** Repeat mode. Null when no repeat surface.
48453
48706
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48454
48707
  repeat: MediaPlayerRepeatSchema.nullable(),
48708
+ /** Ms epoch when `position` was read from the device. Null when the driver
48709
+ * does not say; a UI that advances the position while playing counts from it. */
48710
+ positionUpdatedAt: number().nullable().default(null),
48455
48711
  /** Ms epoch when the slice was last updated. */
48456
48712
  lastChangedAt: number()
48457
48713
  });
@@ -49031,7 +49287,9 @@ var ThresholdTransformDraftSchema = object({
49031
49287
  comparison: _enum(["gte", "lte"]),
49032
49288
  threshold: number(),
49033
49289
  startDwellMs: number().nonnegative(),
49034
- stopDwellMs: number().nonnegative()
49290
+ stopDwellMs: number().nonnegative(),
49291
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49292
+ minSamples: number().int().min(1).optional()
49035
49293
  });
49036
49294
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49037
49295
  IdentityTransformDraftSchema,
@@ -53984,6 +54242,7 @@ var IntegrationWithStateSchema = object({
53984
54242
  id: string(),
53985
54243
  addonId: string(),
53986
54244
  name: string(),
54245
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53987
54246
  enabled: boolean(),
53988
54247
  info: record(string(), unknown()).readonly(),
53989
54248
  /** The discovery candidate this integration was set up from (D984). */
@@ -53996,6 +54255,7 @@ var IntegrationLiteSchema = object({
53996
54255
  id: string(),
53997
54256
  addonId: string(),
53998
54257
  name: string(),
54258
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
53999
54259
  enabled: boolean(),
54000
54260
  info: record(string(), unknown()).readonly(),
54001
54261
  /** The discovery candidate this integration was set up from (D984). */
@@ -54095,7 +54355,6 @@ var TestConnectionResultSchema = object({
54095
54355
  var CreateIntegrationInputSchema = object({
54096
54356
  addonId: string(),
54097
54357
  name: string(),
54098
- enabled: boolean().optional(),
54099
54358
  info: record(string(), unknown()).optional(),
54100
54359
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54101
54360
  originStableId: string().optional(),
@@ -54104,6 +54363,11 @@ var CreateIntegrationInputSchema = object({
54104
54363
  var UpdateIntegrationInputSchema = object({
54105
54364
  id: string(),
54106
54365
  name: string().optional(),
54366
+ /**
54367
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54368
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54369
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54370
+ */
54107
54371
  enabled: boolean().optional(),
54108
54372
  info: record(string(), unknown()).optional()
54109
54373
  });
@@ -54151,7 +54415,7 @@ var IntegrationInstanceIdSchema = string().min(1);
54151
54415
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54152
54416
  /**
54153
54417
  * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54154
- * instance is an integration that brings devices (the registry owns its on/off switch);
54418
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54155
54419
  * `services`: a connection configured from the addon's own function page, never listed on
54156
54420
  * Integrations.
54157
54421
  * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
@@ -54194,18 +54458,38 @@ var IntegrationInstanceKindSchema = object({
54194
54458
  /** Relative hub path to disconnect that account. */
54195
54459
  disconnectPath: string().min(1).optional()
54196
54460
  });
54461
+ /**
54462
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54463
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54464
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54465
+ * instance and its candidates are claimed by it.
54466
+ */
54467
+ var IntegrationInstanceDiscoverySchema = object({
54468
+ mode: _enum([
54469
+ "none",
54470
+ "lan",
54471
+ "account"
54472
+ ]),
54473
+ scopedToInstance: boolean()
54474
+ });
54475
+ /**
54476
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54477
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54478
+ * The hub indexes these so the target's delete is refused while a link names it.
54479
+ */
54480
+ var IntegrationInstanceLinkSchema = object({
54481
+ kind: string().min(1),
54482
+ field: string().min(1),
54483
+ to: object({
54484
+ cap: string().min(1),
54485
+ kind: string().min(1).optional()
54486
+ })
54487
+ });
54197
54488
  var IntegrationInstanceDescriptionSchema = object({
54198
54489
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54199
54490
  role: IntegrationInstanceRoleSchema,
54200
54491
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54201
- discovery: object({
54202
- mode: _enum([
54203
- "none",
54204
- "lan",
54205
- "account"
54206
- ]),
54207
- scopedToInstance: boolean()
54208
- }).optional(),
54492
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54209
54493
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54210
54494
  instanceMode: IntegrationInstanceModeSchema,
54211
54495
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54226,7 +54510,9 @@ var IntegrationInstanceDescriptionSchema = object({
54226
54510
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54227
54511
  * send an id (the UI then mints an opaque one).
54228
54512
  */
54229
- mintsId: boolean().optional()
54513
+ mintsId: boolean().optional(),
54514
+ /** The links to other instances the provider's kinds declare; absent means none. */
54515
+ links: array(IntegrationInstanceLinkSchema).optional()
54230
54516
  });
54231
54517
  var IntegrationInstanceStatusSchema = object({
54232
54518
  state: _enum([
@@ -54246,8 +54532,8 @@ var IntegrationInstanceSchema = object({
54246
54532
  configured: boolean(),
54247
54533
  /**
54248
54534
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54249
- * so a row written before the field existed is on). Absent when the `integrations` registry
54250
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54535
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54536
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54251
54537
  */
54252
54538
  enabled: boolean().optional(),
54253
54539
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54297,7 +54583,8 @@ var integrationInstancesCapability = {
54297
54583
  auth: "admin"
54298
54584
  }),
54299
54585
  /**
54300
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54586
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54587
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54301
54588
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54302
54589
  */
54303
54590
  setInstanceEnabled: method(object({
@@ -57108,6 +57395,8 @@ var MigrationIntegrationSchema = object({
57108
57395
  addonId: string(),
57109
57396
  name: string(),
57110
57397
  info: Rows,
57398
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57399
+ enabled: boolean().optional(),
57111
57400
  originStableId: string().optional()
57112
57401
  });
57113
57402
  var MigrationDeviceSchema = object({
@@ -66626,14 +66915,6 @@ object({
66626
66915
  empty: boolean().nullable(),
66627
66916
  /** True while the pump is running. Null while unknown. */
66628
66917
  pumpRunning: boolean().nullable(),
66629
- /** Water drunk in the last drink, in litres. */
66630
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66631
- /** Water drunk in the current hour, in litres. */
66632
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66633
- /** Water drunk over the last 24 hours (rolling), in litres. */
66634
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66635
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66636
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66637
66918
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66638
66919
  error: string().nullable(),
66639
66920
  /** Ms epoch when the slice was last refreshed. */
@@ -66646,9 +66927,6 @@ DeviceType.PetFountain, method(object({
66646
66927
  }), _void(), {
66647
66928
  kind: "mutation",
66648
66929
  auth: "protected"
66649
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66650
- kind: "mutation",
66651
- auth: "protected"
66652
66930
  });
66653
66931
  /**
66654
66932
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -82035,13 +82313,6 @@ Object.freeze({
82035
82313
  access: "view",
82036
82314
  role: "viewer"
82037
82315
  },
82038
- "petFountain.resetDailyConsumption": {
82039
- capName: "pet-fountain",
82040
- capScope: "device",
82041
- addonId: null,
82042
- access: "delete",
82043
- role: "viewer"
82044
- },
82045
82316
  "petFountain.setPump": {
82046
82317
  capName: "pet-fountain",
82047
82318
  capScope: "device",
@@ -88438,11 +88709,6 @@ Object.freeze({
88438
88709
  form: "single",
88439
88710
  optional: false
88440
88711
  }],
88441
- "petFountain.resetDailyConsumption": [{
88442
- name: "deviceId",
88443
- form: "single",
88444
- optional: false
88445
- }],
88446
88712
  "petFountain.setPump": [{
88447
88713
  name: "deviceId",
88448
88714
  form: "single",
@@ -91186,23 +91452,22 @@ object({
91186
91452
  delay: number().nonnegative().optional(),
91187
91453
  commands: record(string(), unknown())
91188
91454
  });
91189
- var BrokerInUseError = class extends Error {
91190
- brokerId;
91455
+ var InstanceInUseError = class extends Error {
91456
+ instanceId;
91191
91457
  users;
91192
- name = "BrokerInUseError";
91193
- constructor(brokerId, users) {
91194
- super(`broker '${brokerId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91195
- this.brokerId = brokerId;
91458
+ name = "InstanceInUseError";
91459
+ constructor(instanceId, users) {
91460
+ super(`instance '${instanceId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91461
+ this.instanceId = instanceId;
91196
91462
  this.users = users;
91197
91463
  }
91198
91464
  };
91199
- /** Throw {@link BrokerInUseError} when any finder names a user of `brokerId`. */
91200
- async function assertBrokerUnused(brokerId, finders) {
91465
+ /** Throw {@link InstanceInUseError} when any finder names a user of `instanceId`. */
91466
+ async function assertInstanceUnused(instanceId, finders) {
91201
91467
  const users = [];
91202
- for (const finder of finders) users.push(...await finder.find(brokerId));
91203
- if (users.length > 0) throw new BrokerInUseError(brokerId, users);
91468
+ for (const finder of finders) users.push(...await finder.find(instanceId));
91469
+ if (users.length > 0) throw new InstanceInUseError(instanceId, users);
91204
91470
  }
91205
- entryBody({ brokerId: string() });
91206
91471
  //#endregion
91207
91472
  //#region src/relay-record-kinds.ts
91208
91473
  /**
@@ -136170,7 +136435,7 @@ function buildMailboxInstances(records, deps) {
136170
136435
  return {
136171
136436
  ...base,
136172
136437
  deleteInstance: async (input) => {
136173
- await assertBrokerUnused(input.id, [users]);
136438
+ await assertInstanceUnused(input.id, [users]);
136174
136439
  return base.deleteInstance(input);
136175
136440
  }
136176
136441
  };
@@ -145585,7 +145850,7 @@ function buildTransportOptions(body) {
145585
145850
  }
145586
145851
  /** An absent `enabled` means on (D996). */
145587
145852
  function isOn(body) {
145588
- return body.enabled !== false;
145853
+ return isInstanceEnabled(body);
145589
145854
  }
145590
145855
  function coerceAddress(entry) {
145591
145856
  return typeof entry === "string" ? entry : entry.address;