@camstack/addon-mqtt-broker 1.2.151 → 1.2.153

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.
@@ -6021,7 +6021,7 @@ var ZodIssueCode = {
6021
6021
  var ZodFirstPartyTypeKind;
6022
6022
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6023
6023
  //#endregion
6024
- //#region ../types/dist/sleep-DEZaLbiu.mjs
6024
+ //#region ../types/dist/sleep-CmjWurK5.mjs
6025
6025
  /**
6026
6026
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6027
6027
  * window to float samples (D455).
@@ -6705,137 +6705,86 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6705
6705
  blockOwner
6706
6706
  };
6707
6707
  }
6708
- /**
6709
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6710
- * `read`/`write` are the addon-store or device-store accessors. The whole
6711
- * validated value round-trips on every read/write — the schema is the
6712
- * single source of truth for what is persisted, so no hand-listed field
6713
- * set can drop a key on save.
6714
- */
6715
- function createDurableState(deps) {
6716
- const get = async () => {
6717
- const raw = (await deps.read())[deps.key];
6718
- if (raw === void 0) return deps.fallback;
6719
- const parsed = deps.schema.safeParse(raw);
6720
- if (!parsed.success) {
6721
- deps.onParseError?.(deps.key, parsed.error);
6722
- return deps.fallback;
6723
- }
6724
- return parsed.data;
6725
- };
6726
- const set = async (next) => {
6727
- const validated = deps.schema.parse(next);
6728
- await deps.write({ [deps.key]: validated });
6729
- };
6730
- const update = async (fn) => {
6731
- await set(fn(await get()));
6732
- };
6708
+ /** The record calls the one-switch migration makes, over the migration API. */
6709
+ function switchRecordsOverMigrationApi(api) {
6710
+ return { kind: (definition) => {
6711
+ const handle = api.records.kind(definition);
6712
+ return {
6713
+ get: (id) => handle.get({ id }),
6714
+ put: (input, opts) => handle.put({
6715
+ ...input,
6716
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6717
+ }),
6718
+ patch: (id, partial) => handle.patch({
6719
+ id,
6720
+ partial
6721
+ })
6722
+ };
6723
+ } };
6724
+ }
6725
+ function integrationRowsApiOver(api) {
6733
6726
  return {
6734
- get,
6735
- set,
6736
- update
6727
+ list: async () => (await api.integrations.list({})).integrations,
6728
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6729
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6737
6730
  };
6738
6731
  }
6739
- /**
6740
- * Per-node scoping for the shared addon-settings blob.
6741
- *
6742
- * An addon's settings store is hub-central (the `addon-settings` cap is
6743
- * hub-routed — the hub instance answers for every node), so fields whose
6744
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6745
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6746
- * the single shared blob. The SCHEMA field key stays bare: the write path
6747
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6748
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6749
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6750
- *
6751
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6752
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6753
- * schema and routes reads/writes through these helpers.
6754
- *
6755
- * ## No bare-key fallback — deliberate
6756
- *
6757
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6758
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6759
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6760
- * the store is invisible to every node, hub included, so one node's
6761
- * selection can never leak onto another. (This generalizes the
6762
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6763
- * arbitrary set of per-node field keys.)
6764
- *
6765
- * Pure functions only — no I/O, no imports beyond the language. This is a
6766
- * LEAF module: import it via its deep path, never from the root barrel.
6767
- */
6768
- /**
6769
- * Normalize a raw kernel node id to the bare node id used for scoping.
6770
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6771
- * processes; per-node settings are per-NODE, so strip the addon segment.
6772
- * `undefined` / `null` / empty falls back to `'hub'`.
6773
- */
6774
- function normalizeNodeId(raw) {
6775
- if (raw === void 0 || raw === null || raw === "") return "hub";
6776
- const slashIdx = raw.indexOf("/");
6777
- if (slashIdx < 0) return raw;
6778
- const bare = raw.slice(0, slashIdx);
6779
- return bare === "" ? "hub" : bare;
6780
- }
6781
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6782
- function nodeScopedKey(base, nodeId) {
6783
- return `${base}@${normalizeNodeId(nodeId)}`;
6784
- }
6785
- /**
6786
- * Read a node's value for a per-node field from the raw shared store:
6787
- * the node-scoped key when present, otherwise `undefined`.
6788
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6789
- * schema `default` win on `undefined`.
6790
- */
6791
- function readNodeValue(store, base, nodeId) {
6792
- return store[nodeScopedKey(base, nodeId)];
6793
- }
6794
- /**
6795
- * Re-map a UI/settings patch so every bare perNode field persists under the
6796
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6797
- * the write path so a save for one node never clobbers another node's value
6798
- * (and the bare key is never written). Returns a new object — the input
6799
- * patch is not mutated.
6800
- */
6801
- function scopePatch(patch, perNodeKeys, nodeId) {
6802
- const out = {};
6803
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6804
- return out;
6805
- }
6806
- /**
6807
- * Project the raw shared store onto the bare schema keys for ONE node so a
6808
- * UI schema (whose field keys are bare) hydrates from that node's own
6809
- * values:
6810
- *
6811
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6812
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6813
- * legacy key must never hydrate any node — no bare fallback).
6814
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6815
- * each bare perNode key; when the node has no scoped key the bare key is
6816
- * left ABSENT so the field's schema `default` wins.
6817
- *
6818
- * Returns a new object — the input store is not mutated.
6819
- */
6820
- function projectStore(store, perNodeKeys, nodeId) {
6821
- const out = {};
6822
- for (const [key, value] of Object.entries(store)) {
6823
- if (key.includes("@")) continue;
6824
- if (perNodeKeys.has(key)) continue;
6825
- out[key] = value;
6732
+ var PREFIX = "records/";
6733
+ /** The base of every records failure. `detail` is the human part of the message. */
6734
+ var RecordsError = class extends Error {
6735
+ code;
6736
+ detail;
6737
+ constructor(code, detail) {
6738
+ super(`${PREFIX}${code}: ${detail}`);
6739
+ this.name = "RecordsError";
6740
+ this.code = code;
6741
+ this.detail = detail;
6826
6742
  }
6827
- for (const base of perNodeKeys) {
6828
- const value = readNodeValue(store, base, nodeId);
6829
- if (value !== void 0) out[base] = value;
6743
+ };
6744
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6745
+ var RecordSecretUnavailableError = class extends RecordsError {
6746
+ constructor(detail) {
6747
+ super("secret-unavailable", detail);
6748
+ this.name = "RecordSecretUnavailableError";
6830
6749
  }
6831
- return out;
6750
+ };
6751
+ var InvalidRecordError = class extends RecordsError {
6752
+ constructor(detail) {
6753
+ super("invalid-record", detail);
6754
+ this.name = "InvalidRecordError";
6755
+ }
6756
+ };
6757
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6758
+ var DeclarationRefusedError = class extends RecordsError {
6759
+ constructor(detail) {
6760
+ super("declaration-refused", detail);
6761
+ this.name = "DeclarationRefusedError";
6762
+ }
6763
+ };
6764
+ function linkTargetOf(meta) {
6765
+ if (typeof meta !== "object" || meta === null) return void 0;
6766
+ const link = Reflect.get(meta, "link");
6767
+ const parsed = LinkTargetSchema.safeParse(link);
6768
+ return parsed.success ? parsed.data : void 0;
6769
+ }
6770
+ var LinkTargetSchema = object({
6771
+ cap: string().min(1),
6772
+ kind: string().min(1).optional()
6773
+ });
6774
+ /** The links a kind declares, read from the meta of its body fields. */
6775
+ function linksOfKind(kind) {
6776
+ const schema = kind.schema;
6777
+ if (!(schema instanceof ZodObject)) return [];
6778
+ const links = [];
6779
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6780
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6781
+ if (to !== void 0) links.push({
6782
+ field,
6783
+ to
6784
+ });
6785
+ }
6786
+ return links;
6832
6787
  }
6833
- /** Every scope, in the order the guard and the docs list them. */
6834
- var SCOPED_SETTINGS_SCOPES = [
6835
- "cluster",
6836
- "device-defaults",
6837
- "node"
6838
- ];
6839
6788
  /**
6840
6789
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6841
6790
  *
@@ -6970,6 +6919,643 @@ function parseSecretRef(ref) {
6970
6919
  fieldPath
6971
6920
  };
6972
6921
  }
6922
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6923
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6924
+ var RECORD_DATABASES = ["settings", "events"];
6925
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6926
+ var RECORD_CLASSES = [
6927
+ "config",
6928
+ "ledger",
6929
+ "audit",
6930
+ "mirror",
6931
+ "ephemeral"
6932
+ ];
6933
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6934
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6935
+ var RECORD_BATCH_MAX = 1e3;
6936
+ var RECORD_QUERY_MAX = 1e3;
6937
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6938
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6939
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6940
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6941
+ /**
6942
+ * Secret fields of a record, addressed the way a Zod schema declares them
6943
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6944
+ * (`auth.accessToken`, `headers[].value`).
6945
+ *
6946
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6947
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6948
+ * key releases exactly that key's secret.
6949
+ *
6950
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6951
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6952
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6953
+ * leaf names its element: `headers[X-Api].value`.
6954
+ *
6955
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6956
+ */
6957
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6958
+ function parseSecretPath(path) {
6959
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6960
+ return path.split(".").map((raw) => {
6961
+ const each = raw.endsWith("[]");
6962
+ const map = raw.endsWith("{}");
6963
+ const key = each || map ? raw.slice(0, -2) : raw;
6964
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6965
+ return {
6966
+ key,
6967
+ each,
6968
+ map
6969
+ };
6970
+ });
6971
+ }
6972
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6973
+ function secretArrayPrefixes(path) {
6974
+ const segments = parseSecretPath(path);
6975
+ const prefixes = [];
6976
+ const walked = [];
6977
+ for (const segment of segments) {
6978
+ walked.push(segment.key);
6979
+ if (segment.each) prefixes.push(walked.join("."));
6980
+ }
6981
+ return prefixes;
6982
+ }
6983
+ function isRecord$6(value) {
6984
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6985
+ }
6986
+ function elementId(element, idKey, declared, prefix) {
6987
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6988
+ 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`);
6989
+ return id;
6990
+ }
6991
+ /**
6992
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6993
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
6994
+ * result is a new body, `data` is untouched.
6995
+ */
6996
+ var REMOVE_LEAF = Symbol("remove-leaf");
6997
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
6998
+ if (!isRecord$6(node)) return node;
6999
+ const segment = segments[index];
7000
+ if (segment === void 0) return node;
7001
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7002
+ const child = node[segment.key];
7003
+ const keys = [...walkedKeys, segment.key];
7004
+ const last = index === segments.length - 1;
7005
+ if (segment.each) {
7006
+ if (!Array.isArray(child)) return node;
7007
+ const prefix = keys.join(".");
7008
+ const idKey = arrayKeys[prefix];
7009
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7010
+ const mapped = child.map((element) => {
7011
+ const id = elementId(element, idKey, declared, prefix);
7012
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7013
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7014
+ });
7015
+ return {
7016
+ ...node,
7017
+ [segment.key]: mapped
7018
+ };
7019
+ }
7020
+ if (segment.map) {
7021
+ if (!isRecord$6(child)) return node;
7022
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7023
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7024
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7025
+ return [mapKey, visit({
7026
+ declared,
7027
+ concrete,
7028
+ value
7029
+ })];
7030
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7031
+ return {
7032
+ ...node,
7033
+ [segment.key]: Object.fromEntries(kept)
7034
+ };
7035
+ }
7036
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7037
+ if (last) {
7038
+ const replacement = visit({
7039
+ declared,
7040
+ concrete,
7041
+ value: child
7042
+ });
7043
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7044
+ return {
7045
+ ...node,
7046
+ [segment.key]: replacement
7047
+ };
7048
+ }
7049
+ return {
7050
+ ...node,
7051
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7052
+ };
7053
+ }
7054
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7055
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7056
+ let current = data;
7057
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7058
+ return current;
7059
+ }
7060
+ /**
7061
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7062
+ * record's refs never collide with the refs a legacy collection of the same name
7063
+ * already holds during an adoption.
7064
+ */
7065
+ function recordSecretCollection(kind) {
7066
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7067
+ }
7068
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7069
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7070
+ return buildSecretRef({
7071
+ owner,
7072
+ scope: {
7073
+ kind: "row",
7074
+ collection: recordSecretCollection(kind),
7075
+ rowId
7076
+ },
7077
+ fieldPath: concretePath
7078
+ });
7079
+ }
7080
+ /**
7081
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7082
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7083
+ * token. The form hands it to the secret field, which reveals the value by ref
7084
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7085
+ * stored secret (the records door reads a view as KEEP).
7086
+ *
7087
+ * ONE implementation for the entries service and for every addon that serves
7088
+ * its own instances (`RecordIntegrationInstances`).
7089
+ */
7090
+ function isRecord$5(value) {
7091
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7092
+ }
7093
+ function secretViewsOf(owner, kind, id, decl, data) {
7094
+ if (decl.secretPaths.length === 0) return data;
7095
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7096
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7097
+ return {
7098
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7099
+ v: 1,
7100
+ set: true
7101
+ };
7102
+ });
7103
+ return isRecord$5(shown) ? shown : data;
7104
+ }
7105
+ /** The most instances one addon lists (an integrations page, not a table). */
7106
+ var INSTANCES_LIST_MAX = 1e3;
7107
+ /**
7108
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7109
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7110
+ */
7111
+ function isInstanceEnabled(body) {
7112
+ return body.enabled !== false;
7113
+ }
7114
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7115
+ var SWITCH_KEY = "enabled";
7116
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7117
+ function topLevelSecretKeys(paths) {
7118
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7119
+ }
7120
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7121
+ function secretMapKeys(paths) {
7122
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7123
+ }
7124
+ /**
7125
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7126
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7127
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7128
+ */
7129
+ function secretMapPatch(value) {
7130
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7131
+ const out = {};
7132
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7133
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7134
+ return Object.keys(out).length > 0 ? out : null;
7135
+ }
7136
+ var RecordIntegrationInstances = class {
7137
+ records;
7138
+ kind;
7139
+ hooks;
7140
+ handle;
7141
+ secretKeys;
7142
+ secretMaps;
7143
+ nameField;
7144
+ switchListeners = /* @__PURE__ */ new Set();
7145
+ constructor(records, kind, hooks) {
7146
+ this.records = records;
7147
+ this.kind = kind;
7148
+ this.hooks = hooks;
7149
+ this.handle = records.kind(kind);
7150
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7151
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7152
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7153
+ }
7154
+ /**
7155
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7156
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7157
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7158
+ */
7159
+ async readResolved(id) {
7160
+ try {
7161
+ const record = await this.handle.getResolved(id);
7162
+ return record === null ? null : {
7163
+ id,
7164
+ body: record.data,
7165
+ enabled: isInstanceEnabled(record.data),
7166
+ secrets: "resolved"
7167
+ };
7168
+ } catch (err) {
7169
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7170
+ const stored = await this.handle.get(id);
7171
+ if (stored === null) return null;
7172
+ return {
7173
+ id,
7174
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7175
+ enabled: isInstanceEnabled(stored.data),
7176
+ secrets: "unavailable"
7177
+ };
7178
+ }
7179
+ }
7180
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7181
+ async getResolved(id) {
7182
+ return (await this.readResolved(id))?.body ?? null;
7183
+ }
7184
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7185
+ async listResolved() {
7186
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7187
+ const out = [];
7188
+ for (const record of page.records) {
7189
+ const read = await this.readResolved(record.id);
7190
+ if (read !== null) out.push(read);
7191
+ }
7192
+ return out;
7193
+ }
7194
+ viewOf(record) {
7195
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7196
+ const rawName = record.data[this.nameField];
7197
+ const kind = this.hooks.kindOf?.(record.data);
7198
+ const health = this.hooks.health?.(record.data, record.id);
7199
+ return {
7200
+ id: record.id,
7201
+ name: typeof rawName === "string" ? rawName : record.id,
7202
+ configured: this.hooks.configured(record.data),
7203
+ enabled: isInstanceEnabled(record.data),
7204
+ formValues: shown,
7205
+ ...kind !== void 0 ? { kind } : {},
7206
+ ...health?.status !== void 0 ? { status: health.status } : {},
7207
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7208
+ };
7209
+ }
7210
+ describe = async () => {
7211
+ const declared = linksOfKind(this.kind);
7212
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7213
+ kind: this.kind.name,
7214
+ field: link.field,
7215
+ to: link.to
7216
+ })) };
7217
+ return {
7218
+ ...this.hooks.description,
7219
+ ...links,
7220
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7221
+ };
7222
+ };
7223
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7224
+ listInstances = async () => {
7225
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7226
+ };
7227
+ getInstance = async ({ id }) => {
7228
+ const record = await this.handle.get(id);
7229
+ return record === null ? null : this.viewOf(record);
7230
+ };
7231
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7232
+ createInstance = async ({ id, name, kind, values }) => {
7233
+ const minted = id ?? this.hooks.mintId?.({
7234
+ name,
7235
+ ...kind !== void 0 ? { kind } : {}
7236
+ });
7237
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7238
+ await this.handle.put({
7239
+ id: minted,
7240
+ data: this.hooks.initialBody(name, kind)
7241
+ }, { ifRev: 0 });
7242
+ const patch = this.patchOf(values ?? {});
7243
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7244
+ await this.hooks.onChanged?.(minted, "created");
7245
+ return { id: minted };
7246
+ };
7247
+ updateInstance = async ({ id, name, values }) => {
7248
+ const patch = this.patchOf(values);
7249
+ if (name !== void 0) patch[this.nameField] = name;
7250
+ await this.handle.patch(id, patch);
7251
+ await this.hooks.onChanged?.(id, "updated");
7252
+ return { ok: true };
7253
+ };
7254
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7255
+ patchOf(values) {
7256
+ const patch = {};
7257
+ for (const [key, value] of Object.entries(values)) {
7258
+ if (value === void 0) continue;
7259
+ if (key === "enabled") continue;
7260
+ if (this.secretMaps.has(key)) {
7261
+ const entries = secretMapPatch(value);
7262
+ if (entries !== null) patch[key] = entries;
7263
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7264
+ else if (isSecretClear(value)) patch[key] = null;
7265
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7266
+ }
7267
+ return patch;
7268
+ }
7269
+ /**
7270
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7271
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7272
+ * addon reconciles from the record, whichever way it flipped.
7273
+ */
7274
+ onSwitched(listener) {
7275
+ this.switchListeners.add(listener);
7276
+ }
7277
+ /**
7278
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7279
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7280
+ * never configured) gets its record from `initialBody` before the switch is written.
7281
+ */
7282
+ setInstanceEnabled = async ({ id, enabled }) => {
7283
+ if (await this.handle.get(id) === null) await this.handle.put({
7284
+ id,
7285
+ data: this.hooks.initialBody(id)
7286
+ }, { ifRev: 0 });
7287
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7288
+ await this.hooks.onChanged?.(id, "enabled");
7289
+ for (const listener of this.switchListeners) await listener(id, enabled);
7290
+ return { ok: true };
7291
+ };
7292
+ /** The row and its keychain refs go together (the records door). */
7293
+ deleteInstance = async ({ id }) => {
7294
+ await this.handle.delete(id);
7295
+ await this.hooks.onChanged?.(id, "deleted");
7296
+ return { ok: true };
7297
+ };
7298
+ testInstance = async (input) => {
7299
+ if (this.hooks.test === void 0) return {
7300
+ success: false,
7301
+ status: "unsupported",
7302
+ error: "This integration declares no connection test"
7303
+ };
7304
+ return this.hooks.test(input);
7305
+ };
7306
+ /** The flat provider object to hand to `registerProvider`. */
7307
+ toProvider() {
7308
+ return {
7309
+ describe: this.describe,
7310
+ instanceFormSchema: this.instanceFormSchema,
7311
+ listInstances: this.listInstances,
7312
+ getInstance: this.getInstance,
7313
+ createInstance: this.createInstance,
7314
+ updateInstance: this.updateInstance,
7315
+ setInstanceEnabled: this.setInstanceEnabled,
7316
+ deleteInstance: this.deleteInstance,
7317
+ testInstance: this.testInstance
7318
+ };
7319
+ }
7320
+ };
7321
+ /**
7322
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7323
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7324
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7325
+ *
7326
+ * For every registry row of the addon that is OFF:
7327
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7328
+ * (a default integration that never had settings, Reolink's among them);
7329
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7330
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7331
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7332
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7333
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7334
+ *
7335
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7336
+ * which is also why `integrations.list` still answers the stored column at that point.
7337
+ */
7338
+ function registrySwitchToBodyId(addonId, date) {
7339
+ return `${addonId}/${date}-registry-switch-to-body`;
7340
+ }
7341
+ async function moveRegistrySwitchToBody(ports, spec) {
7342
+ const rows = await ports.listIntegrations(spec.addonId);
7343
+ let created = 0;
7344
+ let switched = 0;
7345
+ let kept = 0;
7346
+ for (const row of rows) {
7347
+ if (row.enabled) continue;
7348
+ const body = await ports.readBody(row.id);
7349
+ if (body === null) {
7350
+ if (await ports.createRecord(row.id, {
7351
+ ...spec.initialBody(row.name),
7352
+ ["enabled"]: false
7353
+ }) === "created") created += 1;
7354
+ else kept += 1;
7355
+ continue;
7356
+ }
7357
+ if ("enabled" in body) {
7358
+ kept += 1;
7359
+ continue;
7360
+ }
7361
+ await ports.switchOff(row.id);
7362
+ switched += 1;
7363
+ }
7364
+ const summary = {
7365
+ integrations: rows.length,
7366
+ off: rows.filter((r) => !r.enabled).length,
7367
+ created,
7368
+ switched,
7369
+ kept
7370
+ };
7371
+ return created === 0 && switched === 0 ? {
7372
+ outcome: "already-done",
7373
+ summary
7374
+ } : {
7375
+ outcome: "done",
7376
+ summary
7377
+ };
7378
+ }
7379
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7380
+ function registrySwitchToBodyMigration(spec) {
7381
+ return {
7382
+ meta: {
7383
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7384
+ owner: spec.addonId,
7385
+ level: "addon-state",
7386
+ seq: spec.seq,
7387
+ dependsOn: [],
7388
+ store: "settings",
7389
+ scope: "cluster",
7390
+ onFailure: "block-owner",
7391
+ bodyKind: "procedure",
7392
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7393
+ fixtureMark: "enabled"
7394
+ },
7395
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7396
+ addonId: spec.addonId,
7397
+ initialBody: spec.initialBody
7398
+ })
7399
+ };
7400
+ }
7401
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7402
+ function registrySwitchPortsOver(deps) {
7403
+ const handle = deps.records.kind({
7404
+ name: deps.kind.name,
7405
+ declaration: deps.kind.declaration,
7406
+ schema: record(string(), unknown())
7407
+ });
7408
+ return {
7409
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7410
+ id: i.id,
7411
+ name: i.name,
7412
+ enabled: i.enabled !== false
7413
+ })),
7414
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7415
+ createRecord: async (id, body) => {
7416
+ if (await handle.get(id) !== null) return "exists";
7417
+ await handle.put({
7418
+ id,
7419
+ data: body
7420
+ }, { ifRev: 0 });
7421
+ return "created";
7422
+ },
7423
+ switchOff: async (id) => {
7424
+ await handle.patch(id, { [SWITCH_KEY]: false });
7425
+ }
7426
+ };
7427
+ }
7428
+ /**
7429
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7430
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7431
+ * validated value round-trips on every read/write — the schema is the
7432
+ * single source of truth for what is persisted, so no hand-listed field
7433
+ * set can drop a key on save.
7434
+ */
7435
+ function createDurableState(deps) {
7436
+ const get = async () => {
7437
+ const raw = (await deps.read())[deps.key];
7438
+ if (raw === void 0) return deps.fallback;
7439
+ const parsed = deps.schema.safeParse(raw);
7440
+ if (!parsed.success) {
7441
+ deps.onParseError?.(deps.key, parsed.error);
7442
+ return deps.fallback;
7443
+ }
7444
+ return parsed.data;
7445
+ };
7446
+ const set = async (next) => {
7447
+ const validated = deps.schema.parse(next);
7448
+ await deps.write({ [deps.key]: validated });
7449
+ };
7450
+ const update = async (fn) => {
7451
+ await set(fn(await get()));
7452
+ };
7453
+ return {
7454
+ get,
7455
+ set,
7456
+ update
7457
+ };
7458
+ }
7459
+ /**
7460
+ * Per-node scoping for the shared addon-settings blob.
7461
+ *
7462
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7463
+ * hub-routed — the hub instance answers for every node), so fields whose
7464
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7465
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7466
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7467
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7468
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7469
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7470
+ *
7471
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7472
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7473
+ * schema and routes reads/writes through these helpers.
7474
+ *
7475
+ * ## No bare-key fallback — deliberate
7476
+ *
7477
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7478
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7479
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7480
+ * the store is invisible to every node, hub included, so one node's
7481
+ * selection can never leak onto another. (This generalizes the
7482
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7483
+ * arbitrary set of per-node field keys.)
7484
+ *
7485
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7486
+ * LEAF module: import it via its deep path, never from the root barrel.
7487
+ */
7488
+ /**
7489
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7490
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7491
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7492
+ * `undefined` / `null` / empty falls back to `'hub'`.
7493
+ */
7494
+ function normalizeNodeId(raw) {
7495
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7496
+ const slashIdx = raw.indexOf("/");
7497
+ if (slashIdx < 0) return raw;
7498
+ const bare = raw.slice(0, slashIdx);
7499
+ return bare === "" ? "hub" : bare;
7500
+ }
7501
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7502
+ function nodeScopedKey(base, nodeId) {
7503
+ return `${base}@${normalizeNodeId(nodeId)}`;
7504
+ }
7505
+ /**
7506
+ * Read a node's value for a per-node field from the raw shared store:
7507
+ * the node-scoped key when present, otherwise `undefined`.
7508
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7509
+ * schema `default` win on `undefined`.
7510
+ */
7511
+ function readNodeValue(store, base, nodeId) {
7512
+ return store[nodeScopedKey(base, nodeId)];
7513
+ }
7514
+ /**
7515
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7516
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7517
+ * the write path so a save for one node never clobbers another node's value
7518
+ * (and the bare key is never written). Returns a new object — the input
7519
+ * patch is not mutated.
7520
+ */
7521
+ function scopePatch(patch, perNodeKeys, nodeId) {
7522
+ const out = {};
7523
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7524
+ return out;
7525
+ }
7526
+ /**
7527
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7528
+ * UI schema (whose field keys are bare) hydrates from that node's own
7529
+ * values:
7530
+ *
7531
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7532
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7533
+ * legacy key must never hydrate any node — no bare fallback).
7534
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7535
+ * each bare perNode key; when the node has no scoped key the bare key is
7536
+ * left ABSENT so the field's schema `default` wins.
7537
+ *
7538
+ * Returns a new object — the input store is not mutated.
7539
+ */
7540
+ function projectStore(store, perNodeKeys, nodeId) {
7541
+ const out = {};
7542
+ for (const [key, value] of Object.entries(store)) {
7543
+ if (key.includes("@")) continue;
7544
+ if (perNodeKeys.has(key)) continue;
7545
+ out[key] = value;
7546
+ }
7547
+ for (const base of perNodeKeys) {
7548
+ const value = readNodeValue(store, base, nodeId);
7549
+ if (value !== void 0) out[base] = value;
7550
+ }
7551
+ return out;
7552
+ }
7553
+ /** Every scope, in the order the guard and the docs list them. */
7554
+ var SCOPED_SETTINGS_SCOPES = [
7555
+ "cluster",
7556
+ "device-defaults",
7557
+ "node"
7558
+ ];
6973
7559
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6974
7560
  var KeychainWriteRefusedError = class extends Error {
6975
7561
  fieldPath;
@@ -6980,7 +7566,7 @@ var KeychainWriteRefusedError = class extends Error {
6980
7566
  }
6981
7567
  };
6982
7568
  var KEEP = { kind: "keep" };
6983
- function isRecord$6(value) {
7569
+ function isRecord$4(value) {
6984
7570
  return typeof value === "object" && value !== null && !Array.isArray(value);
6985
7571
  }
6986
7572
  function defaultMintId() {
@@ -6993,7 +7579,7 @@ function collectSecretMarkerRefs(value, out = []) {
6993
7579
  return out;
6994
7580
  }
6995
7581
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6996
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7582
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6997
7583
  return out;
6998
7584
  }
6999
7585
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7048,7 +7634,7 @@ function rowId(row, idKey) {
7048
7634
  return null;
7049
7635
  }
7050
7636
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7051
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7637
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7052
7638
  if (!Array.isArray(incoming)) {
7053
7639
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7054
7640
  return {
@@ -7064,7 +7650,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7064
7650
  const kept = /* @__PURE__ */ new Set();
7065
7651
  const rows = [];
7066
7652
  for (const row of incoming) {
7067
- if (!isRecord$6(row)) {
7653
+ if (!isRecord$4(row)) {
7068
7654
  rows.push(row);
7069
7655
  continue;
7070
7656
  }
@@ -7089,7 +7675,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7089
7675
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7090
7676
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7091
7677
  case "object": {
7092
- if (!isRecord$6(incoming)) {
7678
+ if (!isRecord$4(incoming)) {
7093
7679
  if (incoming === void 0) return KEEP;
7094
7680
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7095
7681
  return {
@@ -7097,7 +7683,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7097
7683
  value: incoming
7098
7684
  };
7099
7685
  }
7100
- const storedObj = isRecord$6(stored) ? stored : {};
7686
+ const storedObj = isRecord$4(stored) ? stored : {};
7101
7687
  return {
7102
7688
  kind: "value",
7103
7689
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7220,7 +7806,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7220
7806
  value: items
7221
7807
  };
7222
7808
  }
7223
- if (isRecord$6(v)) {
7809
+ if (isRecord$4(v)) {
7224
7810
  const out = {};
7225
7811
  for (const [k, child] of Object.entries(v)) {
7226
7812
  const s = substitute(child);
@@ -7252,7 +7838,7 @@ var SecretOverwriteRefusedError = class extends Error {
7252
7838
  this.name = "SecretOverwriteRefusedError";
7253
7839
  }
7254
7840
  };
7255
- function isRecord$5(value) {
7841
+ function isRecord$3(value) {
7256
7842
  return typeof value === "object" && value !== null && !Array.isArray(value);
7257
7843
  }
7258
7844
  function resolvedValue(pass, marker) {
@@ -7281,7 +7867,7 @@ function inArray(pass, incoming, stored) {
7281
7867
  return incoming.map((item, index) => {
7282
7868
  const twin = stored[index];
7283
7869
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7284
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7870
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7285
7871
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7286
7872
  return item;
7287
7873
  });
@@ -7292,7 +7878,7 @@ function inArrayRow(pass, incoming, stored) {
7292
7878
  const twin = stored[key];
7293
7879
  if (isSecretMarker(twin)) {
7294
7880
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7295
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7881
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7296
7882
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7297
7883
  }
7298
7884
  return out;
@@ -7300,7 +7886,7 @@ function inArrayRow(pass, incoming, stored) {
7300
7886
  async function walk(pass, incoming, stored) {
7301
7887
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7302
7888
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7303
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7889
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7304
7890
  const out = { ...incoming };
7305
7891
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7306
7892
  return out;
@@ -7331,7 +7917,7 @@ async function restoreUnchangedSecrets(input) {
7331
7917
  function isJsonEqual(a, b) {
7332
7918
  if (Object.is(a, b)) return true;
7333
7919
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7334
- if (isRecord$5(a) && isRecord$5(b)) {
7920
+ if (isRecord$3(a) && isRecord$3(b)) {
7335
7921
  const keys = Object.keys(a);
7336
7922
  if (keys.length !== Object.keys(b).length) return false;
7337
7923
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7355,7 +7941,7 @@ function markerKeysOf(blob, owner) {
7355
7941
  }
7356
7942
  function nodeFromStored(value, owner) {
7357
7943
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7358
- if (!isRecord$5(value)) return null;
7944
+ if (!isRecord$3(value)) return null;
7359
7945
  const children = /* @__PURE__ */ new Map();
7360
7946
  for (const [key, child] of Object.entries(value)) {
7361
7947
  const node = nodeFromStored(child, owner);
@@ -7650,6 +8236,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7650
8236
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7651
8237
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7652
8238
  /**
8239
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8240
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8241
+ * through `api` (guard `check-migration-ports-surface`).
8242
+ */
8243
+ function migrationSet(catalogue, bindPorts) {
8244
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8245
+ }
8246
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8247
+ function refuseMixed(form, kept, dropped) {
8248
+ if (dropped > 0) throw new Error(`runMigrations(${form}): ${dropped} of ${kept + dropped} entries are of the other kind and would be dropped; pass one kind per call`);
8249
+ }
8250
+ function catalogueOf(list) {
8251
+ const kept = list.filter((entry) => !("execute" in entry));
8252
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8253
+ return kept;
8254
+ }
8255
+ function boundOf(list) {
8256
+ const kept = list.filter((entry) => "execute" in entry);
8257
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8258
+ return kept;
8259
+ }
8260
+ /**
7653
8261
  * Base class for CamStack addons. Eliminates settings boilerplate:
7654
8262
  *
7655
8263
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7816,29 +8424,62 @@ var BaseAddon = class {
7816
8424
  await this.loadScopedSchemas();
7817
8425
  return normalized;
7818
8426
  }
7819
- /**
7820
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7821
- * engine. Call it at the point of the boot where the data must already have the new
7822
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7823
- * restored devices — with the catalogue bound to the addon's ports
7824
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7825
- *
7826
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7827
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7828
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7829
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7830
- *
7831
- * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7832
- * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7833
- * omitted applied ids "newer").
7834
- */
7835
- async runMigrations(migrations, options) {
8427
+ async runMigrations(first, second, third) {
8428
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8429
+ return this.runBound(boundOf(first), second);
8430
+ }
8431
+ /**
8432
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8433
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8434
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
8435
+ */
8436
+ async runMigrationSets(sets, options) {
8437
+ const api = this.ctx.migrationApi;
8438
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8439
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8440
+ }
8441
+ /**
8442
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8443
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8444
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8445
+ * on every declare).
8446
+ */
8447
+ declareRegistrySwitch(spec) {
8448
+ this.registrySwitchSpec = spec;
8449
+ }
8450
+ registrySwitchSpec = null;
8451
+ registrySwitchBound() {
8452
+ const spec = this.registrySwitchSpec;
8453
+ if (spec === null) return [];
8454
+ const api = this.ctx.migrationApi;
8455
+ if (api === void 0) {
8456
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8457
+ return [];
8458
+ }
8459
+ return migrationSet([registrySwitchToBodyMigration({
8460
+ addonId: this.ctx.id,
8461
+ date: "2026-11-06",
8462
+ seq: 1e3,
8463
+ initialBody: spec.initialBody
8464
+ })], (a) => registrySwitchPortsOver({
8465
+ api: integrationRowsApiOver(a),
8466
+ records: switchRecordsOverMigrationApi(a),
8467
+ kind: spec.kind
8468
+ })).bind(api);
8469
+ }
8470
+ async runBound(declared, options) {
8471
+ const added = this.registrySwitchBound();
8472
+ const migrations = [...declared, ...added];
8473
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8474
+ ...options,
8475
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8476
+ };
7836
8477
  const api = this.ctx.api.migrations;
7837
8478
  const report = await runAddonMigrations({
7838
8479
  declareOwner: (input) => api.declareOwner.mutate(input),
7839
8480
  startMigration: (input) => api.startMigration.mutate(input),
7840
8481
  finishMigration: (input) => api.finishMigration.mutate(input)
7841
- }, migrations, this.ctx.logger, options);
8482
+ }, migrations, this.ctx.logger, phased);
7842
8483
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7843
8484
  return report;
7844
8485
  }
@@ -8911,221 +9552,6 @@ function normalizeAddonInitResult(result) {
8911
9552
  if (Array.isArray(result)) return { providers: result };
8912
9553
  return result;
8913
9554
  }
8914
- var PREFIX = "records/";
8915
- /** The base of every records failure. `detail` is the human part of the message. */
8916
- var RecordsError = class extends Error {
8917
- code;
8918
- detail;
8919
- constructor(code, detail) {
8920
- super(`${PREFIX}${code}: ${detail}`);
8921
- this.name = "RecordsError";
8922
- this.code = code;
8923
- this.detail = detail;
8924
- }
8925
- };
8926
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8927
- var RecordSecretUnavailableError = class extends RecordsError {
8928
- constructor(detail) {
8929
- super("secret-unavailable", detail);
8930
- this.name = "RecordSecretUnavailableError";
8931
- }
8932
- };
8933
- var InvalidRecordError = class extends RecordsError {
8934
- constructor(detail) {
8935
- super("invalid-record", detail);
8936
- this.name = "InvalidRecordError";
8937
- }
8938
- };
8939
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8940
- var DeclarationRefusedError = class extends RecordsError {
8941
- constructor(detail) {
8942
- super("declaration-refused", detail);
8943
- this.name = "DeclarationRefusedError";
8944
- }
8945
- };
8946
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8947
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8948
- var RECORD_DATABASES = ["settings", "events"];
8949
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8950
- var RECORD_CLASSES = [
8951
- "config",
8952
- "ledger",
8953
- "audit",
8954
- "mirror",
8955
- "ephemeral"
8956
- ];
8957
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8958
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8959
- var RECORD_BATCH_MAX = 1e3;
8960
- var RECORD_QUERY_MAX = 1e3;
8961
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8962
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8963
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8964
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8965
- /**
8966
- * Secret fields of a record, addressed the way a Zod schema declares them
8967
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8968
- * (`auth.accessToken`, `headers[].value`).
8969
- *
8970
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8971
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8972
- * key releases exactly that key's secret.
8973
- *
8974
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8975
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8976
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8977
- * leaf names its element: `headers[X-Api].value`.
8978
- *
8979
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8980
- */
8981
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8982
- function parseSecretPath(path) {
8983
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8984
- return path.split(".").map((raw) => {
8985
- const each = raw.endsWith("[]");
8986
- const map = raw.endsWith("{}");
8987
- const key = each || map ? raw.slice(0, -2) : raw;
8988
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8989
- return {
8990
- key,
8991
- each,
8992
- map
8993
- };
8994
- });
8995
- }
8996
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8997
- function secretArrayPrefixes(path) {
8998
- const segments = parseSecretPath(path);
8999
- const prefixes = [];
9000
- const walked = [];
9001
- for (const segment of segments) {
9002
- walked.push(segment.key);
9003
- if (segment.each) prefixes.push(walked.join("."));
9004
- }
9005
- return prefixes;
9006
- }
9007
- function isRecord$4(value) {
9008
- return typeof value === "object" && value !== null && !Array.isArray(value);
9009
- }
9010
- function elementId(element, idKey, declared, prefix) {
9011
- const id = isRecord$4(element) ? element[idKey] : void 0;
9012
- 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`);
9013
- return id;
9014
- }
9015
- /**
9016
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9017
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9018
- * result is a new body, `data` is untouched.
9019
- */
9020
- var REMOVE_LEAF = Symbol("remove-leaf");
9021
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9022
- if (!isRecord$4(node)) return node;
9023
- const segment = segments[index];
9024
- if (segment === void 0) return node;
9025
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9026
- const child = node[segment.key];
9027
- const keys = [...walkedKeys, segment.key];
9028
- const last = index === segments.length - 1;
9029
- if (segment.each) {
9030
- if (!Array.isArray(child)) return node;
9031
- const prefix = keys.join(".");
9032
- const idKey = arrayKeys[prefix];
9033
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9034
- const mapped = child.map((element) => {
9035
- const id = elementId(element, idKey, declared, prefix);
9036
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9037
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9038
- });
9039
- return {
9040
- ...node,
9041
- [segment.key]: mapped
9042
- };
9043
- }
9044
- if (segment.map) {
9045
- if (!isRecord$4(child)) return node;
9046
- const kept = Object.entries(child).map(([mapKey, value]) => {
9047
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9048
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9049
- return [mapKey, visit({
9050
- declared,
9051
- concrete,
9052
- value
9053
- })];
9054
- }).filter(([, value]) => value !== REMOVE_LEAF);
9055
- return {
9056
- ...node,
9057
- [segment.key]: Object.fromEntries(kept)
9058
- };
9059
- }
9060
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9061
- if (last) {
9062
- const replacement = visit({
9063
- declared,
9064
- concrete,
9065
- value: child
9066
- });
9067
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9068
- return {
9069
- ...node,
9070
- [segment.key]: replacement
9071
- };
9072
- }
9073
- return {
9074
- ...node,
9075
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9076
- };
9077
- }
9078
- /** Replace/remove every present secret leaf; returns a NEW body. */
9079
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9080
- let current = data;
9081
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9082
- return current;
9083
- }
9084
- /**
9085
- * The keychain collection name a kind's secrets live under. Prefixed so a
9086
- * record's refs never collide with the refs a legacy collection of the same name
9087
- * already holds during an adoption.
9088
- */
9089
- function recordSecretCollection(kind) {
9090
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9091
- }
9092
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9093
- function recordSecretRef(owner, kind, rowId, concretePath) {
9094
- return buildSecretRef({
9095
- owner,
9096
- scope: {
9097
- kind: "row",
9098
- collection: recordSecretCollection(kind),
9099
- rowId
9100
- },
9101
- fieldPath: concretePath
9102
- });
9103
- }
9104
- /**
9105
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9106
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9107
- * token. The form hands it to the secret field, which reveals the value by ref
9108
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9109
- * stored secret (the records door reads a view as KEEP).
9110
- *
9111
- * ONE implementation for the entries service and for every addon that serves
9112
- * its own instances (`RecordIntegrationInstances`).
9113
- */
9114
- function isRecord$3(value) {
9115
- return typeof value === "object" && value !== null && !Array.isArray(value);
9116
- }
9117
- function secretViewsOf(owner, kind, id, decl, data) {
9118
- if (decl.secretPaths.length === 0) return data;
9119
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9120
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9121
- return {
9122
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9123
- v: 1,
9124
- set: true
9125
- };
9126
- });
9127
- return isRecord$3(shown) ? shown : data;
9128
- }
9129
9555
  /**
9130
9556
  * The share-view scope kinds a share-link token can carry. The hub mints
9131
9557
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9379,6 +9805,7 @@ function defineRecordKinds(specs) {
9379
9805
  function entryBody(shape) {
9380
9806
  return object({
9381
9807
  name: string().min(1),
9808
+ enabled: boolean().optional(),
9382
9809
  ...shape
9383
9810
  });
9384
9811
  }
@@ -11218,6 +11645,10 @@ Object.freeze({
11218
11645
  "all",
11219
11646
  "one"
11220
11647
  ]
11648
+ },
11649
+ {
11650
+ "path": "positionUpdatedAt",
11651
+ "valueType": "number"
11221
11652
  }
11222
11653
  ],
11223
11654
  "meter": [{
@@ -11472,22 +11903,6 @@ Object.freeze({
11472
11903
  "path": "pumpRunning",
11473
11904
  "valueType": "boolean"
11474
11905
  },
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
11906
  {
11492
11907
  "path": "error",
11493
11908
  "valueType": "string"
@@ -12053,12 +12468,66 @@ Object.freeze({
12053
12468
  }
12054
12469
  ]
12055
12470
  });
12471
+ Object.freeze({
12472
+ "actions": { "run": 363e4 },
12473
+ "audio-analyzer": { "classify": 3e4 },
12474
+ "custom-model-registry": { "importModelBundle": 18e5 },
12475
+ "database-snapshot": { "writeSnapshot": 18e5 },
12476
+ "device-manager": {
12477
+ "migrateDevice": 72e4,
12478
+ "runDiscoverySweep": 12e4
12479
+ },
12480
+ "device-provider": { "reloadDevice": 18e4 },
12481
+ "llm": {
12482
+ "generate": 6e5,
12483
+ "generateVision": 6e5,
12484
+ "testProfile": 6e5
12485
+ },
12486
+ "llm-runtime": {
12487
+ "complete": 6e5,
12488
+ "completeApple": 6e5,
12489
+ "ensureStarted": 6e5,
12490
+ "installModel": 36e5
12491
+ },
12492
+ "local-network": { "scanNetwork": 9e4 },
12493
+ "model-convert": { "convert": 6e5 },
12494
+ "pipeline-analytics": {
12495
+ "addRetrainFrameFromRecording": 6e4,
12496
+ "offerRetrainArchive": 12e4,
12497
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12498
+ "resolveRetrainTrainingCorpus": 6e4,
12499
+ "writeRetrainArchive": 36e5
12500
+ },
12501
+ "server-management": { "applyServerUpdate": 96e4 },
12502
+ "terminal-session": { "pullOutput": 15e3 },
12503
+ "training": {
12504
+ "canaryResult": 12e4,
12505
+ "cancelJob": 12e4,
12506
+ "planJob": 6e4,
12507
+ "registerResult": 18e5,
12508
+ "rollbackCanary": 12e4,
12509
+ "startJob": 12e4,
12510
+ "startJobBatch": 12e4
12511
+ },
12512
+ "training-provider": {
12513
+ "cancelJob": 6e4,
12514
+ "cleanupJob": 3e5,
12515
+ "getJob": 6e4,
12516
+ "listJobEvents": 6e4,
12517
+ "listJobs": 12e4,
12518
+ "offerArtifact": 3e5,
12519
+ "readResult": 3e5,
12520
+ "submitJob": 18e5,
12521
+ "uploadDataset": 72e5,
12522
+ "validateCredentials": 3e4
12523
+ }
12524
+ });
12056
12525
  object({
12057
12526
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12058
12527
  params: record(string(), union([string(), number()])).optional()
12059
12528
  });
12060
12529
  //#endregion
12061
- //#region ../types/dist/composition-pOHbTzRB.mjs
12530
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12062
12531
  /**
12063
12532
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12064
12533
  *
@@ -12362,7 +12831,7 @@ var table = {
12362
12831
  },
12363
12832
  dwell: {
12364
12833
  minArgs: 3,
12365
- maxArgs: 3,
12834
+ maxArgs: 4,
12366
12835
  apply: () => {
12367
12836
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12368
12837
  }
@@ -13405,205 +13874,6 @@ var IntegrationInstanceRefSchema = object({
13405
13874
  ]),
13406
13875
  candidateStableId: string().optional()
13407
13876
  });
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 }) => {
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
- await this.hooks.onChanged?.(minted, "created");
13553
- return { id: minted };
13554
- };
13555
- updateInstance = async ({ id, name, values }) => {
13556
- const patch = {};
13557
- for (const [key, value] of Object.entries(values)) {
13558
- if (value === void 0) continue;
13559
- if (this.secretMaps.has(key)) {
13560
- const entries = secretMapPatch(value);
13561
- if (entries !== null) patch[key] = entries;
13562
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13563
- else if (isSecretClear(value)) patch[key] = null;
13564
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13565
- }
13566
- if (name !== void 0) patch[this.nameField] = name;
13567
- await this.handle.patch(id, patch);
13568
- await this.hooks.onChanged?.(id, "updated");
13569
- return { ok: true };
13570
- };
13571
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13572
- setInstanceEnabled = async ({ id, enabled }) => {
13573
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13574
- await this.handle.patch(id, { enabled });
13575
- await this.hooks.onChanged?.(id, "enabled");
13576
- return { ok: true };
13577
- };
13578
- /** The row and its keychain refs go together (the records door). */
13579
- deleteInstance = async ({ id }) => {
13580
- await this.handle.delete(id);
13581
- await this.hooks.onChanged?.(id, "deleted");
13582
- return { ok: true };
13583
- };
13584
- testInstance = async (input) => {
13585
- if (this.hooks.test === void 0) return {
13586
- success: false,
13587
- status: "unsupported",
13588
- error: "This integration declares no connection test"
13589
- };
13590
- return this.hooks.test(input);
13591
- };
13592
- /** The flat provider object to hand to `registerProvider`. */
13593
- toProvider() {
13594
- return {
13595
- describe: this.describe,
13596
- instanceFormSchema: this.instanceFormSchema,
13597
- listInstances: this.listInstances,
13598
- getInstance: this.getInstance,
13599
- createInstance: this.createInstance,
13600
- updateInstance: this.updateInstance,
13601
- setInstanceEnabled: this.setInstanceEnabled,
13602
- deleteInstance: this.deleteInstance,
13603
- testInstance: this.testInstance
13604
- };
13605
- }
13606
- };
13607
13877
  var EncodeProfileSchema = object({
13608
13878
  video: object({
13609
13879
  codec: _enum([
@@ -15776,6 +16046,39 @@ var UnstampedEventMediaCountSchema = object({
15776
16046
  /** Sum across both, or `null` when either lane could not be counted. */
15777
16047
  total: number().int().nonnegative().nullable()
15778
16048
  }).nullable();
16049
+ /**
16050
+ * Where the stored event media sits, per storage location: how many media rows
16051
+ * and how many bytes carry each location id, how many carry none (legacy,
16052
+ * resolved to the default `eventMedia` location), and how many name a location
16053
+ * that was not asked about (a deleted or never-listed one).
16054
+ *
16055
+ * One covering-index aggregate per asked location plus the NULL one, and one
16056
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16057
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16058
+ * it is a deleted location only when every location id was asked.
16059
+ * `null` is "could not be measured", never zero.
16060
+ */
16061
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16062
+ var MediaLocationCensusSchema = object({
16063
+ locations: array(object({
16064
+ locationId: string(),
16065
+ rows: number().int().nonnegative(),
16066
+ bytes: number().nonnegative()
16067
+ })).readonly(),
16068
+ unstamped: object({
16069
+ rows: number().int().nonnegative(),
16070
+ bytes: number().nonnegative()
16071
+ }),
16072
+ /** Rows stamped with a location id that was not in the asked list. */
16073
+ unlisted: object({
16074
+ rows: number().int().nonnegative(),
16075
+ bytes: number().nonnegative()
16076
+ }),
16077
+ total: object({
16078
+ rows: number().int().nonnegative(),
16079
+ bytes: number().nonnegative()
16080
+ })
16081
+ });
15779
16082
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15780
16083
  /** The independently selectable logical storage classes — every class
15781
16084
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -19755,31 +20058,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19755
20058
  "pet-fountain": {
19756
20059
  scope: "device",
19757
20060
  noun: t("Pet fountain", "Fontana per animali"),
19758
- actions: [
19759
- {
19760
- id: "petFountain.pumpOn",
19761
- method: "setPump",
19762
- label: t("Pump on", "Pompa accesa"),
19763
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19764
- icon: "play",
19765
- args: { on: true }
19766
- },
19767
- {
19768
- id: "petFountain.pumpOff",
19769
- method: "setPump",
19770
- label: t("Pump off", "Pompa spenta"),
19771
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19772
- icon: "square",
19773
- args: { on: false }
19774
- },
19775
- {
19776
- id: "petFountain.resetDailyConsumption",
19777
- method: "resetDailyConsumption",
19778
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19779
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19780
- icon: "rotate-ccw"
19781
- }
19782
- ],
20061
+ actions: [{
20062
+ id: "petFountain.pumpOn",
20063
+ method: "setPump",
20064
+ label: t("Pump on", "Pompa accesa"),
20065
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20066
+ icon: "play",
20067
+ args: { on: true }
20068
+ }, {
20069
+ id: "petFountain.pumpOff",
20070
+ method: "setPump",
20071
+ label: t("Pump off", "Pompa spenta"),
20072
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20073
+ icon: "square",
20074
+ args: { on: false }
20075
+ }],
19783
20076
  state: [{
19784
20077
  kind: "boolean",
19785
20078
  field: "empty",
@@ -43673,8 +43966,15 @@ var ActionInputSchema = object({
43673
43966
  var ActionRunOriginSchema = object({
43674
43967
  /** The automation block whose step started it. */
43675
43968
  blockId: string().min(1).optional() });
43676
- /** `started` = the caller did not ask to wait. */
43677
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
43969
+ /**
43970
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
43971
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
43972
+ */
43973
+ var ActionRunOutcomeSchema = union([
43974
+ AutomationRunOutcomeSchema,
43975
+ literal("started"),
43976
+ literal("timed-out")
43977
+ ]);
43678
43978
  var ActionRunResultSchema = object({
43679
43979
  runId: string().min(1),
43680
43980
  outcome: ActionRunOutcomeSchema,
@@ -44196,6 +44496,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44196
44496
  kind: "mutation",
44197
44497
  auth: "admin"
44198
44498
  });
44499
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44500
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44199
44501
  /**
44200
44502
  * actions — the ONE surface for runnable actions, for the UI and for
44201
44503
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44214,6 +44516,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44214
44516
  * An admin, and an in-process caller (an automation block), may run any action.
44215
44517
  * Every refusal is typed (`[not-linked] …`) and logged.
44216
44518
  *
44519
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44520
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44521
+ * `wait` steps alone add up to more is refused at create/update
44522
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44523
+ * waited call (an automation step) is never cut by the 60 s transport default.
44524
+ *
44217
44525
  * A second `run` of an action that is already running is REFUSED — traced and
44218
44526
  * logged — never queued.
44219
44527
  */
@@ -44240,7 +44548,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44240
44548
  role: "viewer",
44241
44549
  auth: "protected",
44242
44550
  kind: "mutation",
44243
- caller: "required"
44551
+ caller: "required",
44552
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44244
44553
  }), method(ActionIdInput, _void(), {
44245
44554
  kind: "mutation",
44246
44555
  auth: "admin"
@@ -46296,52 +46605,7 @@ DeviceType.Light, method(object({
46296
46605
  level: number().min(0).max(100),
46297
46606
  lastChangedAt: number()
46298
46607
  });
46299
- /**
46300
- * `broker` — unified pub/sub broker registry, system-scoped collection.
46301
- *
46302
- * The cap models any kind-tagged message broker the user wants to
46303
- * register and that other addons might consume. The first two kinds
46304
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
46305
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
46306
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
46307
- * the same surface.
46308
- *
46309
- * Why one cap, not one cap per kind:
46310
- * - The integrations page wants a single table of "every broker"
46311
- * across kinds; a unified cap drives it without join logic.
46312
- * - Generic admin operations (add / remove / test / status) are
46313
- * identical across kinds — duplicating them per cap was busywork.
46314
- * - The `network-access` cap precedent: same interface, many
46315
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
46316
- *
46317
- * What stays kind-specific:
46318
- * - `getBrokerConfig` payload (kind decides whether it returns
46319
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
46320
- * `Record<string, unknown>` at the wire; consumers narrow.
46321
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
46322
- * key) — also typed as `Record<string, unknown>` so each kind can
46323
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
46324
- * without rebreaking the cap signature.
46325
- * - `add` `settings` payload (different fields per kind, validated by
46326
- * the kind-specific provider).
46327
- *
46328
- * Bidirectionality:
46329
- * - `publish` is RPC — synchronous result (provider-defined).
46330
- * - `subscribe` returns a subscription handle; the actual message
46331
- * stream flows over the typed event-bus as `broker.message` events
46332
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
46333
- * event handler. Subscriptions persist across reconnects — the
46334
- * provider re-subscribes upstream after a transport drop.
46335
- *
46336
- * Why event-bus push (not a subscription RPC stream):
46337
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
46338
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
46339
- * drop is recoverable via `getState({key})`).
46340
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
46341
- * - Cross-process: events already route through `$event-bus`; no
46342
- * per-broker wire-shaping needed.
46343
- */
46344
- var BrokerStatusEnum = _enum([
46608
+ _enum([
46345
46609
  "connected",
46346
46610
  "disconnected",
46347
46611
  "connecting",
@@ -46349,141 +46613,12 @@ var BrokerStatusEnum = _enum([
46349
46613
  "unreachable",
46350
46614
  "error"
46351
46615
  ]);
46352
- var BrokerInfoSchema = object({
46353
- /** Stable broker id. Persisted; survives addon restarts. */
46354
- id: string(),
46355
- /** Addon id of the provider that OWNS this broker.
46356
- *
46357
- * The `broker` cap is a system-scoped collection: several addons
46358
- * register a `broker` provider, each owning a DISJOINT set of
46359
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
46360
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
46361
- * device belongs to one integration. The admin UI threads this id
46362
- * back as the `{ addonId }` system-collection selector on every
46363
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
46364
- * `testConnection`), so the call routes to the OWNING provider
46365
- * instead of defaulting to the first-registered one. */
46366
- addonId: string(),
46367
- /** Human-readable name (operator-chosen at add-time). */
46368
- name: string(),
46369
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
46370
- kind: string(),
46371
- status: BrokerStatusEnum,
46372
- /** Free-form provider-specific info (HA version, MQTT broker
46373
- * flavour, latency, mTLS active, …). */
46374
- info: record(string(), unknown()),
46375
- /** Ms epoch of the last connection probe / status update. */
46376
- lastCheckedAt: number().nullable(),
46377
- /** Last error message, when `status` indicates failure. */
46378
- error: string().nullable()
46379
- });
46380
46616
  var RegistryStatusSchema = object({
46381
46617
  brokerCount: number().int().nonnegative(),
46382
46618
  connectedCount: number().int().nonnegative()
46383
46619
  });
46384
- /**
46385
- * One entry per `broker` provider — which addon provides which broker
46386
- * kind(s). The unified create picker reads this to know, for each
46387
- * (addonId, kind) pair the operator can pick, where to route the
46388
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
46389
- * `{ addonId }` selector). A provider only advertises a kind here when
46390
- * it implements `getSettingsSchema` for that kind (so the picker never
46391
- * offers a kind whose creation form can't be rendered).
46392
- */
46393
- var BrokerProviderInfoSchema = object({
46394
- /** Addon id of the `broker` provider this entry describes. */
46395
- addonId: string(),
46396
- /** Broker kinds this provider can create, with a display label. */
46397
- kinds: array(object({
46398
- kind: string(),
46399
- label: string(),
46400
- /**
46401
- * Relative hub path to start an interactive account link (OAuth popup).
46402
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
46403
- */
46404
- interactiveConnectPath: string().min(1).optional(),
46405
- /** Relative hub path to disconnect the linked account (same popup pattern). */
46406
- interactiveDisconnectPath: string().min(1).optional(),
46407
- /**
46408
- * The kind signs in through a server-held interactive session instead of
46409
- * (or before) typed credentials. `basePath` is a hub-relative route set
46410
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
46411
- * contract: `POST {basePath}/start` (body: the form's settings) answers
46412
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
46413
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
46414
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
46415
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
46416
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
46417
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
46418
- * offers it as the default path; the fields the session fills are
46419
- * marked `filledBySignIn` in the kind's settings schema.
46420
- *
46421
- * `methods` lists the ways the session can sign in, recommended first:
46422
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
46423
- * settings) answering `{ sessionId, userCode, verificationUrl,
46424
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
46425
- * any device, and the same `status` / `commit` / `cancel` routes follow
46426
- * (status then carries `method`, `userCode`, `verificationUrl`,
46427
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
46428
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
46429
- * `['proxy']`.
46430
- */
46431
- signIn: object({
46432
- basePath: string().min(1),
46433
- methods: array(_enum(["device-code", "proxy"])).optional()
46434
- }).optional()
46435
- }))
46436
- });
46437
- var ListInputSchema = object({
46438
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
46439
- * only HA brokers. Omit to list every broker. */
46440
- kind: string().optional() });
46441
46620
  var GetInputSchema = object({ id: string() });
46442
- var AddInputSchema = object({
46443
- kind: string().min(1),
46444
- name: string().min(1),
46445
- /**
46446
- * ADOPT an existing id instead of minting a new one.
46447
- *
46448
- * Written the day this cost an outage. A broker's id is not a detail: HA
46449
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
46450
- * lost from config and re-added as `ha_001` leaves every one of its devices
46451
- * bound to a broker that no longer exists. Re-entering the password under the
46452
- * ORIGINAL id turns a multi-step device migration back into re-entering a
46453
- * password.
46454
- *
46455
- * A provider MUST refuse an id that is already in use — adopting a live
46456
- * broker's id would silently take it over.
46457
- */
46458
- id: string().min(1).optional(),
46459
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
46460
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
46461
- * branch on receipt — invalid shape rejects the add. */
46462
- settings: record(string(), unknown())
46463
- });
46464
- var AddResultSchema = object({ id: string() });
46465
- var RemoveInputSchema = object({ id: string() });
46466
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
46467
- ok: literal(true),
46468
- latencyMs: number().nonnegative()
46469
- }), object({
46470
- ok: literal(false),
46471
- error: string()
46472
- })]);
46473
46621
  var SettingsRecordSchema$1 = record(string(), unknown());
46474
- var SettingsSchemaInputSchema = object({ kind: string() });
46475
- var TestSettingsInputSchema = object({
46476
- kind: string(),
46477
- settings: SettingsRecordSchema$1
46478
- });
46479
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
46480
- ok: literal(true),
46481
- latencyMs: number().nonnegative().optional()
46482
- }).strict(), object({
46483
- ok: literal(false),
46484
- error: string()
46485
- })]);
46486
- var SettingsSchemaResultSchema = unknown().nullable();
46487
46622
  var PublishInputSchema = object({
46488
46623
  brokerId: string(),
46489
46624
  /** Kind-specific routing target.
@@ -46527,51 +46662,12 @@ var brokerCapability = {
46527
46662
  kind: "poll"
46528
46663
  },
46529
46664
  methods: {
46530
- list: method(ListInputSchema, array(BrokerInfoSchema)),
46531
- get: method(GetInputSchema, BrokerInfoSchema.nullable()),
46532
- /** Enumerate which addon provides which broker kind(s) for the
46533
- * unified create picker. The auto-mount fans this array across
46534
- * every registered `broker` provider (array-output method), so the
46535
- * picker sees every kind from every provider in one call. */
46536
- listProviders: method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }),
46537
- add: method(AddInputSchema, AddResultSchema, {
46538
- kind: "mutation",
46539
- auth: "admin"
46540
- }),
46541
- remove: method(RemoveInputSchema, _void(), {
46542
- kind: "mutation",
46543
- auth: "admin"
46544
- }),
46545
- testConnection: method(GetInputSchema, TestConnectionResultSchema, {
46546
- kind: "mutation",
46547
- auth: "admin"
46548
- }),
46549
- /** Read the persisted settings record for a broker (kind-specific
46550
- * shape). Admin-only — settings may contain secrets. Returns `null`
46551
- * when the broker id is unknown to the provider (the collection
46552
- * fallback may route a foreign id to the first provider). */
46553
- getSettings: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46554
- /** Overwrite the persisted settings record. The kind-specific
46555
- * provider validates the shape and applies the change (reconnects
46556
- * if credentials changed). */
46557
- setSettings: method(object({
46558
- id: string(),
46559
- settings: SettingsRecordSchema$1
46560
- }), _void(), {
46561
- kind: "mutation",
46562
- auth: "admin"
46563
- }),
46564
46665
  /** Returns the kind-specific connection config the consumer needs
46565
46666
  * to open its own client (MQTT pattern: `{url, username, password,
46566
46667
  * clientIdPrefix}`). HA providers MAY return the auth envelope
46567
46668
  * but typical HA consumers use `publish` / `subscribe` instead.
46568
46669
  * Returns `null` when the broker id is unknown to the provider. */
46569
46670
  getBrokerConfig: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46570
- getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }),
46571
- testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, {
46572
- kind: "mutation",
46573
- auth: "admin"
46574
- }),
46575
46671
  publish: method(PublishInputSchema, unknown(), {
46576
46672
  kind: "mutation",
46577
46673
  auth: "admin"
@@ -48498,6 +48594,9 @@ var MediaPlayerStatusSchema = object({
48498
48594
  /** Repeat mode. Null when no repeat surface.
48499
48595
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48500
48596
  repeat: MediaPlayerRepeatSchema.nullable(),
48597
+ /** Ms epoch when `position` was read from the device. Null when the driver
48598
+ * does not say; a UI that advances the position while playing counts from it. */
48599
+ positionUpdatedAt: number().nullable().default(null),
48501
48600
  /** Ms epoch when the slice was last updated. */
48502
48601
  lastChangedAt: number()
48503
48602
  });
@@ -49077,7 +49176,9 @@ var ThresholdTransformDraftSchema = object({
49077
49176
  comparison: _enum(["gte", "lte"]),
49078
49177
  threshold: number(),
49079
49178
  startDwellMs: number().nonnegative(),
49080
- stopDwellMs: number().nonnegative()
49179
+ stopDwellMs: number().nonnegative(),
49180
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49181
+ minSamples: number().int().min(1).optional()
49081
49182
  });
49082
49183
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49083
49184
  IdentityTransformDraftSchema,
@@ -50644,7 +50745,14 @@ var DiscoveryCandidateSchema = object({
50644
50745
  /** `stableId` of the gateway candidate this device was found BEHIND. */
50645
50746
  parentStableId: string().optional(),
50646
50747
  /** `false` = shown for context but not pickable. Default true. */
50647
- selectable: boolean().optional()
50748
+ selectable: boolean().optional(),
50749
+ /**
50750
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
50751
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
50752
+ * admin asks for exactly these, on the creation form prefilled with
50753
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
50754
+ */
50755
+ needsParams: array(string()).optional()
50648
50756
  });
50649
50757
  /**
50650
50758
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -50703,12 +50811,24 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
50703
50811
  }), array(DiscoveryCandidateSchema), {
50704
50812
  kind: "mutation",
50705
50813
  auth: "admin"
50706
- }), method(object({}), CreationSchemaOutputSchema), method(object({}), object({ deviceType: _enum(DeviceType).nullable() })), method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
50814
+ }), method(object({}), CreationSchemaOutputSchema), method(object({
50815
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50816
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })), method(object({
50817
+ candidate: DiscoveryCandidateSchema,
50818
+ /** The integration the operator adopts into; a provider with several instances needs it. */
50819
+ integrationId: string().optional()
50820
+ }), DeviceSummarySchema, {
50707
50821
  kind: "mutation",
50708
50822
  auth: "admin"
50709
- }), method(object({}), boolean()), method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema), method(object({
50823
+ }), method(object({}), boolean()), method(object({
50710
50824
  type: _enum(DeviceType),
50711
- config: record(string(), unknown())
50825
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50826
+ integrationId: string().optional()
50827
+ }), CreationSchemaOutputSchema), method(object({
50828
+ type: _enum(DeviceType),
50829
+ config: record(string(), unknown()),
50830
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
50831
+ integrationId: string().optional()
50712
50832
  }), DeviceSummarySchema, {
50713
50833
  kind: "mutation",
50714
50834
  auth: "admin"
@@ -51418,7 +51538,10 @@ method(object({
51418
51538
  auth: "admin"
51419
51539
  }), method(object({
51420
51540
  addonId: string(),
51421
- type: _enum(DeviceType)
51541
+ type: _enum(DeviceType),
51542
+ /** The integration the form is for; a provider whose integrations differ (a hub
51543
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
51544
+ integrationId: string().optional()
51422
51545
  }), unknown().nullable()), method(object({
51423
51546
  addonId: string(),
51424
51547
  type: _enum(DeviceType),
@@ -51502,7 +51625,11 @@ method(object({
51502
51625
  kind: "mutation",
51503
51626
  auth: "admin",
51504
51627
  timeoutMs: 12e4
51505
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51628
+ }), method(object({
51629
+ addonId: string(),
51630
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
51631
+ integrationId: string().optional()
51632
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51506
51633
  deviceId: number(),
51507
51634
  key: string(),
51508
51635
  value: unknown()
@@ -54004,6 +54131,7 @@ var IntegrationWithStateSchema = object({
54004
54131
  id: string(),
54005
54132
  addonId: string(),
54006
54133
  name: string(),
54134
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54007
54135
  enabled: boolean(),
54008
54136
  info: record(string(), unknown()).readonly(),
54009
54137
  /** The discovery candidate this integration was set up from (D984). */
@@ -54016,6 +54144,7 @@ var IntegrationLiteSchema = object({
54016
54144
  id: string(),
54017
54145
  addonId: string(),
54018
54146
  name: string(),
54147
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54019
54148
  enabled: boolean(),
54020
54149
  info: record(string(), unknown()).readonly(),
54021
54150
  /** The discovery candidate this integration was set up from (D984). */
@@ -54098,7 +54227,7 @@ var TestConnectionStatusEnum = _enum([
54098
54227
  "inconclusive",
54099
54228
  "unsupported"
54100
54229
  ]);
54101
- var TestConnectionResultSchema$1 = object({
54230
+ var TestConnectionResultSchema = object({
54102
54231
  /** True ONLY for `validated`. Never true for a test that did not run. */
54103
54232
  success: boolean(),
54104
54233
  error: string().optional(),
@@ -54115,7 +54244,6 @@ var TestConnectionResultSchema$1 = object({
54115
54244
  var CreateIntegrationInputSchema = object({
54116
54245
  addonId: string(),
54117
54246
  name: string(),
54118
- enabled: boolean().optional(),
54119
54247
  info: record(string(), unknown()).optional(),
54120
54248
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54121
54249
  originStableId: string().optional(),
@@ -54124,6 +54252,11 @@ var CreateIntegrationInputSchema = object({
54124
54252
  var UpdateIntegrationInputSchema = object({
54125
54253
  id: string(),
54126
54254
  name: string().optional(),
54255
+ /**
54256
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54257
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54258
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54259
+ */
54127
54260
  enabled: boolean().optional(),
54128
54261
  info: record(string(), unknown()).optional()
54129
54262
  });
@@ -54143,7 +54276,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54143
54276
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54144
54277
  addonId: string(),
54145
54278
  settings: record(string(), unknown())
54146
- }), TestConnectionResultSchema$1, {
54279
+ }), TestConnectionResultSchema, {
54147
54280
  kind: "mutation",
54148
54281
  auth: "admin"
54149
54282
  });
@@ -54170,6 +54303,14 @@ var ConfigSchemaPassthrough$3 = custom();
54170
54303
  var IntegrationInstanceIdSchema = string().min(1);
54171
54304
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54172
54305
  /**
54306
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54307
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54308
+ * `services`: a connection configured from the addon's own function page, never listed on
54309
+ * Integrations.
54310
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
54311
+ */
54312
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
54313
+ /**
54173
54314
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54174
54315
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54175
54316
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -54180,6 +54321,22 @@ var IntegrationInstanceKindSchema = object({
54180
54321
  /** Stable id of the kind, sent back as `createInstance.kind`. */
54181
54322
  id: string().min(1),
54182
54323
  label: string().min(1),
54324
+ /**
54325
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
54326
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
54327
+ * provider with more than one section must name it on every kind.
54328
+ */
54329
+ functionCap: string().min(1),
54330
+ /**
54331
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
54332
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
54333
+ * finds the instances whose kind names it; absent takes the kind `id`.
54334
+ */
54335
+ brokerKind: string().min(1).optional(),
54336
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
54337
+ role: IntegrationInstanceRoleSchema.optional(),
54338
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
54339
+ canTest: boolean().optional(),
54183
54340
  /** The kind signs in through a server-held interactive session. */
54184
54341
  signIn: object({
54185
54342
  basePath: string().min(1),
@@ -54190,22 +54347,38 @@ var IntegrationInstanceKindSchema = object({
54190
54347
  /** Relative hub path to disconnect that account. */
54191
54348
  disconnectPath: string().min(1).optional()
54192
54349
  });
54350
+ /**
54351
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54352
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54353
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54354
+ * instance and its candidates are claimed by it.
54355
+ */
54356
+ var IntegrationInstanceDiscoverySchema = object({
54357
+ mode: _enum([
54358
+ "none",
54359
+ "lan",
54360
+ "account"
54361
+ ]),
54362
+ scopedToInstance: boolean()
54363
+ });
54364
+ /**
54365
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54366
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54367
+ * The hub indexes these so the target's delete is refused while a link names it.
54368
+ */
54369
+ var IntegrationInstanceLinkSchema = object({
54370
+ kind: string().min(1),
54371
+ field: string().min(1),
54372
+ to: object({
54373
+ cap: string().min(1),
54374
+ kind: string().min(1).optional()
54375
+ })
54376
+ });
54193
54377
  var IntegrationInstanceDescriptionSchema = object({
54194
54378
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54195
- role: _enum([
54196
- "devices",
54197
- "services",
54198
- "both"
54199
- ]),
54379
+ role: IntegrationInstanceRoleSchema,
54200
54380
  /** 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(),
54381
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54209
54382
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54210
54383
  instanceMode: IntegrationInstanceModeSchema,
54211
54384
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54226,7 +54399,9 @@ var IntegrationInstanceDescriptionSchema = object({
54226
54399
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54227
54400
  * send an id (the UI then mints an opaque one).
54228
54401
  */
54229
- mintsId: boolean().optional()
54402
+ mintsId: boolean().optional(),
54403
+ /** The links to other instances the provider's kinds declare; absent means none. */
54404
+ links: array(IntegrationInstanceLinkSchema).optional()
54230
54405
  });
54231
54406
  var IntegrationInstanceStatusSchema = object({
54232
54407
  state: _enum([
@@ -54246,8 +54421,8 @@ var IntegrationInstanceSchema = object({
54246
54421
  configured: boolean(),
54247
54422
  /**
54248
54423
  * 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.
54424
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54425
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54251
54426
  */
54252
54427
  enabled: boolean().optional(),
54253
54428
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54271,7 +54446,11 @@ var integrationInstancesCapability = {
54271
54446
  methods: {
54272
54447
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54273
54448
  /** The form; `id: null` is the create form. */
54274
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54449
+ instanceFormSchema: method(object({
54450
+ id: IntegrationInstanceIdSchema.nullable(),
54451
+ /** The kind of the create form (`id: null`) of a provider with several. */
54452
+ kind: string().min(1).optional()
54453
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54275
54454
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54276
54455
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54277
54456
  /**
@@ -54281,7 +54460,9 @@ var integrationInstancesCapability = {
54281
54460
  createInstance: method(object({
54282
54461
  id: IntegrationInstanceIdSchema.optional(),
54283
54462
  name: string().min(1),
54284
- kind: string().min(1).optional()
54463
+ kind: string().min(1).optional(),
54464
+ /** Form values written with the record (a link picked in the create dialog). */
54465
+ values: record(string(), unknown()).optional()
54285
54466
  }), object({ id: string() }), {
54286
54467
  kind: "mutation",
54287
54468
  auth: "admin"
@@ -54291,7 +54472,8 @@ var integrationInstancesCapability = {
54291
54472
  auth: "admin"
54292
54473
  }),
54293
54474
  /**
54294
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54475
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54476
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54295
54477
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54296
54478
  */
54297
54479
  setInstanceEnabled: method(object({
@@ -54308,8 +54490,10 @@ var integrationInstancesCapability = {
54308
54490
  }),
54309
54491
  testInstance: optionalMethod(object({
54310
54492
  id: IntegrationInstanceIdSchema.nullable(),
54311
- values: record(string(), unknown())
54312
- }), TestConnectionResultSchema$1, {
54493
+ values: record(string(), unknown()),
54494
+ /** The kind to test when `id` is null and the provider has several. */
54495
+ kind: string().min(1).optional()
54496
+ }), TestConnectionResultSchema, {
54313
54497
  kind: "mutation",
54314
54498
  auth: "admin"
54315
54499
  })
@@ -56814,6 +56998,382 @@ var SystemMetricsSchema = object({
56814
56998
  gpuMemoryPercent: number().optional()
56815
56999
  });
56816
57000
  method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(GetLoadSeriesInputSchema, NodeLoadSeriesSchema);
57001
+ /**
57002
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
57003
+ * config documents, mirrors. The third storage API next to `ctx.settings`
57004
+ * (operator intent, D870) and device-history (numbers over time, D850).
57005
+ *
57006
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
57007
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
57008
+ * that with the addon id closed over). It is deliberately NOT in any input
57009
+ * schema, so a session can never supply it, and a call with no stamp is refused
57010
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
57011
+ * addons go through the owner's capability.
57012
+ *
57013
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
57014
+ * never `[]`. Secret fields are never on the wire: a read shows the
57015
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
57016
+ * resolves itself, and a write may carry only a keychain marker bound to the
57017
+ * row's own ref.
57018
+ *
57019
+ * Internal: addons reach it through `ctx.records`, never directly.
57020
+ */
57021
+ var RecordIdSchema = string().min(1).max(256);
57022
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
57023
+ var RecordBodySchema = record(string(), unknown());
57024
+ var RecordInputSchema = object({
57025
+ id: RecordIdSchema,
57026
+ /** The device this row belongs to (D865 removal, per-device reads). */
57027
+ deviceId: number().int().optional(),
57028
+ /** The domain clock, ms: observed / created / opened. */
57029
+ at: number().int().optional(),
57030
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
57031
+ expiresAt: number().int().optional(),
57032
+ data: RecordBodySchema
57033
+ });
57034
+ var RecordViewSchema = object({
57035
+ id: string(),
57036
+ deviceId: number().int().nullable(),
57037
+ at: number().nullable(),
57038
+ expiresAt: number().nullable(),
57039
+ rev: number().int(),
57040
+ updatedAt: number(),
57041
+ data: RecordBodySchema
57042
+ });
57043
+ /** Declared index fields only. Anything else does not compile, by design. */
57044
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
57045
+ string(),
57046
+ number(),
57047
+ boolean(),
57048
+ object({ in: array(union([
57049
+ string(),
57050
+ number(),
57051
+ boolean()
57052
+ ])).min(1).max(RECORD_BATCH_MAX) }),
57053
+ object({
57054
+ gt: union([string(), number()]).optional(),
57055
+ gte: union([string(), number()]).optional(),
57056
+ lt: union([string(), number()]).optional(),
57057
+ lte: union([string(), number()]).optional()
57058
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
57059
+ ]));
57060
+ var KindShape = { kind: RecordKindNameSchema };
57061
+ var TimeWindowShape = {
57062
+ deviceId: number().int().optional(),
57063
+ atFrom: number().optional(),
57064
+ atTo: number().optional()
57065
+ };
57066
+ var RecordQueryInputSchema = object({
57067
+ ...KindShape,
57068
+ ...TimeWindowShape,
57069
+ where: RecordWhereSchema.optional(),
57070
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
57071
+ order: _enum(["at", "id"]).optional(),
57072
+ desc: boolean().optional(),
57073
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
57074
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
57075
+ cursor: string().min(1).optional()
57076
+ });
57077
+ var RecordQueryResultSchema = object({
57078
+ records: array(RecordViewSchema),
57079
+ nextCursor: string().nullable()
57080
+ });
57081
+ var RecordKindStateSchema = _enum([
57082
+ "created",
57083
+ "unchanged",
57084
+ "updated"
57085
+ ]);
57086
+ var DeclareKindResultSchema = object({
57087
+ kindId: number().int(),
57088
+ state: RecordKindStateSchema,
57089
+ createdIndexes: array(string())
57090
+ });
57091
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
57092
+ var SecretRefsList = array(string());
57093
+ /**
57094
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
57095
+ * All ops of one call share ONE database file and ONE `transactFamily`.
57096
+ */
57097
+ var RecordTransactOpSchema = discriminatedUnion("op", [
57098
+ object({
57099
+ op: literal("put"),
57100
+ kind: RecordKindNameSchema,
57101
+ record: RecordInputSchema,
57102
+ ifRev: number().int().min(0).optional()
57103
+ }),
57104
+ object({
57105
+ op: literal("patch"),
57106
+ kind: RecordKindNameSchema,
57107
+ id: RecordIdSchema,
57108
+ data: RecordBodySchema,
57109
+ at: number().int().nullable().optional(),
57110
+ expiresAt: number().int().nullable().optional(),
57111
+ ifRev: number().int().min(1).optional()
57112
+ }),
57113
+ object({
57114
+ op: literal("delete"),
57115
+ kind: RecordKindNameSchema,
57116
+ id: RecordIdSchema
57117
+ })
57118
+ ]);
57119
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
57120
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
57121
+ kind: "mutation",
57122
+ auth: "admin"
57123
+ }), method(object({
57124
+ ...KindShape,
57125
+ id: RecordIdSchema
57126
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
57127
+ ...KindShape,
57128
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57129
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
57130
+ ...KindShape,
57131
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57132
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
57133
+ ...KindShape,
57134
+ record: RecordInputSchema,
57135
+ /** Compare-and-set. `0` means "the row must not exist". */
57136
+ ifRev: number().int().min(0).optional()
57137
+ }), object({
57138
+ rev: number().int(),
57139
+ releasedRefs: SecretRefsList
57140
+ }), {
57141
+ kind: "mutation",
57142
+ auth: "admin"
57143
+ }), method(object({
57144
+ ...KindShape,
57145
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
57146
+ }), object({
57147
+ count: number().int(),
57148
+ releasedRefs: SecretRefsList
57149
+ }), {
57150
+ kind: "mutation",
57151
+ auth: "admin"
57152
+ }), method(object({
57153
+ ...KindShape,
57154
+ id: RecordIdSchema,
57155
+ data: RecordBodySchema,
57156
+ at: number().int().nullable().optional(),
57157
+ expiresAt: number().int().nullable().optional(),
57158
+ ifRev: number().int().min(1).optional()
57159
+ }), object({
57160
+ rev: number().int(),
57161
+ releasedRefs: SecretRefsList
57162
+ }), {
57163
+ kind: "mutation",
57164
+ auth: "admin"
57165
+ }), method(object({
57166
+ ...KindShape,
57167
+ id: RecordIdSchema
57168
+ }), object({
57169
+ deleted: boolean(),
57170
+ secretRefs: SecretRefsList
57171
+ }), {
57172
+ kind: "mutation",
57173
+ auth: "admin"
57174
+ }), method(object({
57175
+ ...KindShape,
57176
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57177
+ }), object({
57178
+ deleted: number().int(),
57179
+ secretRefs: SecretRefsList
57180
+ }), {
57181
+ kind: "mutation",
57182
+ auth: "admin"
57183
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
57184
+ ...KindShape,
57185
+ ...TimeWindowShape,
57186
+ where: RecordWhereSchema.optional()
57187
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
57188
+ ...KindShape,
57189
+ deviceId: number().int().optional(),
57190
+ from: number(),
57191
+ to: number(),
57192
+ bucketMs: number().int().positive()
57193
+ }), object({ buckets: array(object({
57194
+ bucketStart: number(),
57195
+ count: number().int()
57196
+ })) }), { auth: "admin" }), method(object({
57197
+ ...KindShape,
57198
+ op: _enum([
57199
+ "sum",
57200
+ "min",
57201
+ "max",
57202
+ "count"
57203
+ ]),
57204
+ field: RecordFieldPathSchema.optional(),
57205
+ groupBy: RecordFieldPathSchema.optional(),
57206
+ where: RecordWhereSchema.optional()
57207
+ }), object({ rows: array(object({
57208
+ group: union([
57209
+ string(),
57210
+ number(),
57211
+ _null()
57212
+ ]),
57213
+ value: number().nullable()
57214
+ })) }), { auth: "admin" }), method(object({
57215
+ ...KindShape,
57216
+ deviceId: number().int().optional(),
57217
+ atBefore: number().optional(),
57218
+ where: RecordWhereSchema.optional()
57219
+ }), object({
57220
+ deleted: number().int(),
57221
+ secretRefs: SecretRefsList
57222
+ }), {
57223
+ kind: "mutation",
57224
+ auth: "admin"
57225
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
57226
+ results: array(object({
57227
+ rev: number().int().nullable(),
57228
+ deleted: boolean()
57229
+ })),
57230
+ releasedRefs: SecretRefsList,
57231
+ secretRefs: SecretRefsList
57232
+ }), {
57233
+ kind: "mutation",
57234
+ auth: "admin"
57235
+ }), method(object({
57236
+ deviceId: number().int(),
57237
+ kinds: array(RecordKindNameSchema).optional()
57238
+ }), object({
57239
+ deleted: record(string(), number().int()),
57240
+ secretRefs: SecretRefsList
57241
+ }), {
57242
+ kind: "mutation",
57243
+ auth: "admin"
57244
+ }), method(object(KindShape), object({ id: number().int() }), {
57245
+ kind: "mutation",
57246
+ auth: "admin"
57247
+ });
57248
+ /**
57249
+ * The wire shapes of the migration API, version 1 (planning#447).
57250
+ *
57251
+ * A migration is code that outlives the server it was written against: an addon at
57252
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
57253
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
57254
+ * is the contract of every method of it, one Zod pair per method.
57255
+ *
57256
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
57257
+ * field is never removed or made required, an enum never narrows, an output field is
57258
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
57259
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
57260
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
57261
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
57262
+ */
57263
+ var Rows = record(string(), unknown());
57264
+ var IntegrationId = object({ integrationId: string().min(1) });
57265
+ var RecordId = object({ id: string().min(1) });
57266
+ var RecordRowSchema = object({
57267
+ id: string(),
57268
+ deviceId: number().int().nullable(),
57269
+ at: number().nullable(),
57270
+ expiresAt: number().nullable(),
57271
+ rev: number().int(),
57272
+ updatedAt: number(),
57273
+ data: Rows
57274
+ });
57275
+ var RecordPutShape = {
57276
+ id: string().min(1),
57277
+ deviceId: number().int().optional(),
57278
+ at: number().int().optional(),
57279
+ expiresAt: number().int().optional(),
57280
+ data: Rows
57281
+ };
57282
+ var MigrationIntegrationSchema = object({
57283
+ id: string(),
57284
+ addonId: string(),
57285
+ name: string(),
57286
+ info: Rows,
57287
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57288
+ enabled: boolean().optional(),
57289
+ originStableId: string().optional()
57290
+ });
57291
+ var MigrationDeviceSchema = object({
57292
+ id: number().int(),
57293
+ integrationId: string().nullable().optional(),
57294
+ /** The owning device; null or absent for a root. */
57295
+ parentDeviceId: number().int().nullable().optional(),
57296
+ type: string().optional(),
57297
+ name: string().optional(),
57298
+ stableId: string().optional()
57299
+ });
57300
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
57301
+ var MigrationApiInfoSchema = object({
57302
+ version: number().int(),
57303
+ methods: array(string())
57304
+ });
57305
+ object({
57306
+ message: string(),
57307
+ meta: Rows.optional(),
57308
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
57309
+ tags: object({ deviceId: number().int().optional() }).optional()
57310
+ });
57311
+ object({
57312
+ owner: string().min(1),
57313
+ metas: array(MigrationMetaSchema)
57314
+ }), object({
57315
+ bootId: string(),
57316
+ snapshot: _enum([
57317
+ "none",
57318
+ "written",
57319
+ "refused"
57320
+ ]),
57321
+ steps: array(MigrationOwnerStepSchema),
57322
+ /** The migration API the engine serves; absent from a server that predates it. */
57323
+ migrationApi: MigrationApiInfoSchema.optional()
57324
+ }), object({ id: string().min(1) }), object({
57325
+ proceed: boolean(),
57326
+ state: union([literal("pending"), MigrationStatusSchema]),
57327
+ reason: string().nullable()
57328
+ }), object({
57329
+ id: string().min(1),
57330
+ result: MigrationOwnerResultSchema
57331
+ }), object({
57332
+ status: MigrationStatusSchema,
57333
+ error: string().nullable(),
57334
+ rowsChanged: number().int().nonnegative()
57335
+ }), object({
57336
+ rows: number().int().nonnegative(),
57337
+ secrets: number().int().nonnegative()
57338
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
57339
+ present: boolean(),
57340
+ removed: Rows
57341
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
57342
+ ...RecordPutShape,
57343
+ ifRev: number().int().optional()
57344
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
57345
+ partial: Rows,
57346
+ ifRev: number().int().optional()
57347
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
57348
+ deviceId: number().int().optional(),
57349
+ atFrom: number().optional(),
57350
+ atTo: number().optional(),
57351
+ where: RecordWhereSchema.optional(),
57352
+ limit: number().int().min(1).optional(),
57353
+ cursor: string().min(1).optional(),
57354
+ resolveSecrets: boolean().optional()
57355
+ }), object({
57356
+ records: array(RecordRowSchema),
57357
+ nextCursor: string().nullable()
57358
+ }), object({
57359
+ deviceId: number().int().optional(),
57360
+ atBefore: number().optional(),
57361
+ where: RecordWhereSchema.optional()
57362
+ }), object({ count: number().int().nonnegative() }), object({}), object({ store: Rows }), object({ patch: Rows }), object({}), object({ keys: array(string().min(1)) }), object({ removed: array(string()) }), object({ refs: array(string()) }), object({ values: record(string(), string().nullable()) }), object({
57363
+ ref: string().min(1),
57364
+ value: string()
57365
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
57366
+ addonId: string().min(1),
57367
+ integrationId: string().min(1).optional()
57368
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
57369
+ id: number().int(),
57370
+ integrationId: string().nullable(),
57371
+ /** Whether the device carries any stored config; its content is not offered. */
57372
+ hasConfig: boolean()
57373
+ }).nullable(), object({
57374
+ deviceId: number().int(),
57375
+ integrationId: string().min(1)
57376
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
56817
57377
  method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { auth: "admin" }), method(object({ owner: string().optional() }), object({ pending: array(MigrationPendingEntrySchema) }), { auth: "admin" }), method(object({ id: string().min(1) }), MigrationDryRunResultSchema, { auth: "admin" }), method(object({
56818
57378
  id: string().min(1),
56819
57379
  error: string().min(1)
@@ -56843,7 +57403,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
56843
57403
  "written",
56844
57404
  "refused"
56845
57405
  ]),
56846
- steps: array(MigrationOwnerStepSchema)
57406
+ steps: array(MigrationOwnerStepSchema),
57407
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
57408
+ migrationApi: MigrationApiInfoSchema.optional()
56847
57409
  }), {
56848
57410
  kind: "mutation",
56849
57411
  auth: "admin"
@@ -59510,7 +60072,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
59510
60072
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
59511
60073
  kind: "mutation",
59512
60074
  auth: "admin"
59513
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
60075
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
60076
+ kind: "query",
60077
+ auth: "admin"
60078
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
59514
60079
  kind: "query",
59515
60080
  auth: "admin"
59516
60081
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -61917,7 +62482,7 @@ var BrokerStatusSchema$1 = _enum([
61917
62482
  "unreachable",
61918
62483
  "tls-error"
61919
62484
  ]);
61920
- var BrokerInfoSchema$1 = object({
62485
+ var BrokerInfoSchema = object({
61921
62486
  id: string(),
61922
62487
  name: string(),
61923
62488
  url: string(),
@@ -61990,7 +62555,7 @@ var mqttBrokerCapability = {
61990
62555
  kind: "poll"
61991
62556
  },
61992
62557
  methods: {
61993
- listBrokers: method(_void(), array(BrokerInfoSchema$1)),
62558
+ listBrokers: method(_void(), array(BrokerInfoSchema)),
61994
62559
  getBrokerConfig: method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }),
61995
62560
  addBroker: method(AddBrokerInputSchema, AddBrokerResultSchema, {
61996
62561
  kind: "mutation",
@@ -66258,14 +66823,6 @@ object({
66258
66823
  empty: boolean().nullable(),
66259
66824
  /** True while the pump is running. Null while unknown. */
66260
66825
  pumpRunning: boolean().nullable(),
66261
- /** Water drunk in the last drink, in litres. */
66262
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66263
- /** Water drunk in the current hour, in litres. */
66264
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66265
- /** Water drunk over the last 24 hours (rolling), in litres. */
66266
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66267
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66268
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66269
66826
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66270
66827
  error: string().nullable(),
66271
66828
  /** Ms epoch when the slice was last refreshed. */
@@ -66278,9 +66835,6 @@ DeviceType.PetFountain, method(object({
66278
66835
  }), _void(), {
66279
66836
  kind: "mutation",
66280
66837
  auth: "protected"
66281
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66282
- kind: "mutation",
66283
- auth: "protected"
66284
66838
  });
66285
66839
  /**
66286
66840
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -68317,253 +68871,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
68317
68871
  auth: "admin"
68318
68872
  });
68319
68873
  /**
68320
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
68321
- * config documents, mirrors. The third storage API next to `ctx.settings`
68322
- * (operator intent, D870) and device-history (numbers over time, D850).
68323
- *
68324
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
68325
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
68326
- * that with the addon id closed over). It is deliberately NOT in any input
68327
- * schema, so a session can never supply it, and a call with no stamp is refused
68328
- * `records/no-caller`. A kind is readable and writable only by its owner; other
68329
- * addons go through the owner's capability.
68330
- *
68331
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
68332
- * never `[]`. Secret fields are never on the wire: a read shows the
68333
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
68334
- * resolves itself, and a write may carry only a keychain marker bound to the
68335
- * row's own ref.
68336
- *
68337
- * Internal: addons reach it through `ctx.records`, never directly.
68338
- */
68339
- var RecordIdSchema = string().min(1).max(256);
68340
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
68341
- var RecordBodySchema = record(string(), unknown());
68342
- var RecordInputSchema = object({
68343
- id: RecordIdSchema,
68344
- /** The device this row belongs to (D865 removal, per-device reads). */
68345
- deviceId: number().int().optional(),
68346
- /** The domain clock, ms: observed / created / opened. */
68347
- at: number().int().optional(),
68348
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
68349
- expiresAt: number().int().optional(),
68350
- data: RecordBodySchema
68351
- });
68352
- var RecordViewSchema = object({
68353
- id: string(),
68354
- deviceId: number().int().nullable(),
68355
- at: number().nullable(),
68356
- expiresAt: number().nullable(),
68357
- rev: number().int(),
68358
- updatedAt: number(),
68359
- data: RecordBodySchema
68360
- });
68361
- /** Declared index fields only. Anything else does not compile, by design. */
68362
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
68363
- string(),
68364
- number(),
68365
- boolean(),
68366
- object({ in: array(union([
68367
- string(),
68368
- number(),
68369
- boolean()
68370
- ])).min(1).max(RECORD_BATCH_MAX) }),
68371
- object({
68372
- gt: union([string(), number()]).optional(),
68373
- gte: union([string(), number()]).optional(),
68374
- lt: union([string(), number()]).optional(),
68375
- lte: union([string(), number()]).optional()
68376
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
68377
- ]));
68378
- var KindShape = { kind: RecordKindNameSchema };
68379
- var TimeWindowShape = {
68380
- deviceId: number().int().optional(),
68381
- atFrom: number().optional(),
68382
- atTo: number().optional()
68383
- };
68384
- var RecordQueryInputSchema = object({
68385
- ...KindShape,
68386
- ...TimeWindowShape,
68387
- where: RecordWhereSchema.optional(),
68388
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
68389
- order: _enum(["at", "id"]).optional(),
68390
- desc: boolean().optional(),
68391
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
68392
- /** Opaque keyset cursor from a previous answer. There is no offset. */
68393
- cursor: string().min(1).optional()
68394
- });
68395
- var RecordQueryResultSchema = object({
68396
- records: array(RecordViewSchema),
68397
- nextCursor: string().nullable()
68398
- });
68399
- var RecordKindStateSchema = _enum([
68400
- "created",
68401
- "unchanged",
68402
- "updated"
68403
- ]);
68404
- var DeclareKindResultSchema = object({
68405
- kindId: number().int(),
68406
- state: RecordKindStateSchema,
68407
- createdIndexes: array(string())
68408
- });
68409
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
68410
- var SecretRefsList = array(string());
68411
- /**
68412
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
68413
- * All ops of one call share ONE database file and ONE `transactFamily`.
68414
- */
68415
- var RecordTransactOpSchema = discriminatedUnion("op", [
68416
- object({
68417
- op: literal("put"),
68418
- kind: RecordKindNameSchema,
68419
- record: RecordInputSchema,
68420
- ifRev: number().int().min(0).optional()
68421
- }),
68422
- object({
68423
- op: literal("patch"),
68424
- kind: RecordKindNameSchema,
68425
- id: RecordIdSchema,
68426
- data: RecordBodySchema,
68427
- at: number().int().nullable().optional(),
68428
- expiresAt: number().int().nullable().optional(),
68429
- ifRev: number().int().min(1).optional()
68430
- }),
68431
- object({
68432
- op: literal("delete"),
68433
- kind: RecordKindNameSchema,
68434
- id: RecordIdSchema
68435
- })
68436
- ]);
68437
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
68438
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
68439
- kind: "mutation",
68440
- auth: "admin"
68441
- }), method(object({
68442
- ...KindShape,
68443
- id: RecordIdSchema
68444
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
68445
- ...KindShape,
68446
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68447
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
68448
- ...KindShape,
68449
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68450
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
68451
- ...KindShape,
68452
- record: RecordInputSchema,
68453
- /** Compare-and-set. `0` means "the row must not exist". */
68454
- ifRev: number().int().min(0).optional()
68455
- }), object({
68456
- rev: number().int(),
68457
- releasedRefs: SecretRefsList
68458
- }), {
68459
- kind: "mutation",
68460
- auth: "admin"
68461
- }), method(object({
68462
- ...KindShape,
68463
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
68464
- }), object({
68465
- count: number().int(),
68466
- releasedRefs: SecretRefsList
68467
- }), {
68468
- kind: "mutation",
68469
- auth: "admin"
68470
- }), method(object({
68471
- ...KindShape,
68472
- id: RecordIdSchema,
68473
- data: RecordBodySchema,
68474
- at: number().int().nullable().optional(),
68475
- expiresAt: number().int().nullable().optional(),
68476
- ifRev: number().int().min(1).optional()
68477
- }), object({
68478
- rev: number().int(),
68479
- releasedRefs: SecretRefsList
68480
- }), {
68481
- kind: "mutation",
68482
- auth: "admin"
68483
- }), method(object({
68484
- ...KindShape,
68485
- id: RecordIdSchema
68486
- }), object({
68487
- deleted: boolean(),
68488
- secretRefs: SecretRefsList
68489
- }), {
68490
- kind: "mutation",
68491
- auth: "admin"
68492
- }), method(object({
68493
- ...KindShape,
68494
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68495
- }), object({
68496
- deleted: number().int(),
68497
- secretRefs: SecretRefsList
68498
- }), {
68499
- kind: "mutation",
68500
- auth: "admin"
68501
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
68502
- ...KindShape,
68503
- ...TimeWindowShape,
68504
- where: RecordWhereSchema.optional()
68505
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
68506
- ...KindShape,
68507
- deviceId: number().int().optional(),
68508
- from: number(),
68509
- to: number(),
68510
- bucketMs: number().int().positive()
68511
- }), object({ buckets: array(object({
68512
- bucketStart: number(),
68513
- count: number().int()
68514
- })) }), { auth: "admin" }), method(object({
68515
- ...KindShape,
68516
- op: _enum([
68517
- "sum",
68518
- "min",
68519
- "max",
68520
- "count"
68521
- ]),
68522
- field: RecordFieldPathSchema.optional(),
68523
- groupBy: RecordFieldPathSchema.optional(),
68524
- where: RecordWhereSchema.optional()
68525
- }), object({ rows: array(object({
68526
- group: union([
68527
- string(),
68528
- number(),
68529
- _null()
68530
- ]),
68531
- value: number().nullable()
68532
- })) }), { auth: "admin" }), method(object({
68533
- ...KindShape,
68534
- deviceId: number().int().optional(),
68535
- atBefore: number().optional(),
68536
- where: RecordWhereSchema.optional()
68537
- }), object({
68538
- deleted: number().int(),
68539
- secretRefs: SecretRefsList
68540
- }), {
68541
- kind: "mutation",
68542
- auth: "admin"
68543
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
68544
- results: array(object({
68545
- rev: number().int().nullable(),
68546
- deleted: boolean()
68547
- })),
68548
- releasedRefs: SecretRefsList,
68549
- secretRefs: SecretRefsList
68550
- }), {
68551
- kind: "mutation",
68552
- auth: "admin"
68553
- }), method(object({
68554
- deviceId: number().int(),
68555
- kinds: array(RecordKindNameSchema).optional()
68556
- }), object({
68557
- deleted: record(string(), number().int()),
68558
- secretRefs: SecretRefsList
68559
- }), {
68560
- kind: "mutation",
68561
- auth: "admin"
68562
- }), method(object(KindShape), object({ id: number().int() }), {
68563
- kind: "mutation",
68564
- auth: "admin"
68565
- });
68566
- /**
68567
68874
  * record-entries - the ONE admin surface for every list of user-created entries
68568
68875
  * (D881): notification targets, brokers, LLM profiles, anything an addon
68569
68876
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -77106,20 +77413,6 @@ Object.freeze({
77106
77413
  access: "create",
77107
77414
  role: "viewer"
77108
77415
  },
77109
- "broker.add": {
77110
- capName: "broker",
77111
- capScope: "system",
77112
- addonId: null,
77113
- access: "create",
77114
- role: "admin"
77115
- },
77116
- "broker.get": {
77117
- capName: "broker",
77118
- capScope: "system",
77119
- addonId: null,
77120
- access: "view",
77121
- role: "admin"
77122
- },
77123
77416
  "broker.getBrokerConfig": {
77124
77417
  capName: "broker",
77125
77418
  capScope: "system",
@@ -77127,20 +77420,6 @@ Object.freeze({
77127
77420
  access: "view",
77128
77421
  role: "admin"
77129
77422
  },
77130
- "broker.getSettings": {
77131
- capName: "broker",
77132
- capScope: "system",
77133
- addonId: null,
77134
- access: "view",
77135
- role: "admin"
77136
- },
77137
- "broker.getSettingsSchema": {
77138
- capName: "broker",
77139
- capScope: "system",
77140
- addonId: null,
77141
- access: "view",
77142
- role: "admin"
77143
- },
77144
77423
  "broker.getState": {
77145
77424
  capName: "broker",
77146
77425
  capScope: "system",
@@ -77155,20 +77434,6 @@ Object.freeze({
77155
77434
  access: "view",
77156
77435
  role: "admin"
77157
77436
  },
77158
- "broker.list": {
77159
- capName: "broker",
77160
- capScope: "system",
77161
- addonId: null,
77162
- access: "view",
77163
- role: "admin"
77164
- },
77165
- "broker.listProviders": {
77166
- capName: "broker",
77167
- capScope: "system",
77168
- addonId: null,
77169
- access: "view",
77170
- role: "admin"
77171
- },
77172
77437
  "broker.publish": {
77173
77438
  capName: "broker",
77174
77439
  capScope: "system",
@@ -77176,20 +77441,6 @@ Object.freeze({
77176
77441
  access: "create",
77177
77442
  role: "admin"
77178
77443
  },
77179
- "broker.remove": {
77180
- capName: "broker",
77181
- capScope: "system",
77182
- addonId: null,
77183
- access: "delete",
77184
- role: "admin"
77185
- },
77186
- "broker.setSettings": {
77187
- capName: "broker",
77188
- capScope: "system",
77189
- addonId: null,
77190
- access: "create",
77191
- role: "admin"
77192
- },
77193
77444
  "broker.subscribe": {
77194
77445
  capName: "broker",
77195
77446
  capScope: "system",
@@ -77197,20 +77448,6 @@ Object.freeze({
77197
77448
  access: "create",
77198
77449
  role: "admin"
77199
77450
  },
77200
- "broker.testConnection": {
77201
- capName: "broker",
77202
- capScope: "system",
77203
- addonId: null,
77204
- access: "create",
77205
- role: "admin"
77206
- },
77207
- "broker.testSettings": {
77208
- capName: "broker",
77209
- capScope: "system",
77210
- addonId: null,
77211
- access: "create",
77212
- role: "admin"
77213
- },
77214
77451
  "broker.unsubscribe": {
77215
77452
  capName: "broker",
77216
77453
  capScope: "system",
@@ -81971,13 +82208,6 @@ Object.freeze({
81971
82208
  access: "view",
81972
82209
  role: "viewer"
81973
82210
  },
81974
- "petFountain.resetDailyConsumption": {
81975
- capName: "pet-fountain",
81976
- capScope: "device",
81977
- addonId: null,
81978
- access: "delete",
81979
- role: "viewer"
81980
- },
81981
82211
  "petFountain.setPump": {
81982
82212
  capName: "pet-fountain",
81983
82213
  capScope: "device",
@@ -82174,6 +82404,13 @@ Object.freeze({
82174
82404
  access: "view",
82175
82405
  role: "viewer"
82176
82406
  },
82407
+ "pipelineAnalytics.getMediaLocationCensus": {
82408
+ capName: "pipeline-analytics",
82409
+ capScope: "device",
82410
+ addonId: null,
82411
+ access: "view",
82412
+ role: "admin"
82413
+ },
82177
82414
  "pipelineAnalytics.getMediaReclaimStatus": {
82178
82415
  capName: "pipeline-analytics",
82179
82416
  capScope: "device",
@@ -88367,11 +88604,6 @@ Object.freeze({
88367
88604
  form: "single",
88368
88605
  optional: false
88369
88606
  }],
88370
- "petFountain.resetDailyConsumption": [{
88371
- name: "deviceId",
88372
- form: "single",
88373
- optional: false
88374
- }],
88375
88607
  "petFountain.setPump": [{
88376
88608
  name: "deviceId",
88377
88609
  form: "single",
@@ -91115,6 +91347,53 @@ object({
91115
91347
  delay: number().nonnegative().optional(),
91116
91348
  commands: record(string(), unknown())
91117
91349
  });
91350
+ var InstanceInUseError = class extends Error {
91351
+ instanceId;
91352
+ users;
91353
+ name = "InstanceInUseError";
91354
+ constructor(instanceId, users) {
91355
+ super(`instance '${instanceId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91356
+ this.instanceId = instanceId;
91357
+ this.users = users;
91358
+ }
91359
+ };
91360
+ /** Throw {@link InstanceInUseError} when any finder names a user of `instanceId`. */
91361
+ async function assertInstanceUnused(instanceId, finders) {
91362
+ const users = [];
91363
+ for (const finder of finders) users.push(...await finder.find(instanceId));
91364
+ if (users.length > 0) throw new InstanceInUseError(instanceId, users);
91365
+ }
91366
+ function namesInstance(value, instanceId) {
91367
+ if (Array.isArray(value)) return value.includes(instanceId);
91368
+ return value === instanceId;
91369
+ }
91370
+ /**
91371
+ * Users reached through another addon's listed rows (an addon cannot read a record kind it does
91372
+ * not own): every row whose `field` holds the instance id, as a string or in a string list.
91373
+ * `list` is a cap call the owner serves.
91374
+ */
91375
+ function fieldUserFinder(spec) {
91376
+ const fields = typeof spec.field === "string" ? [spec.field] : spec.field;
91377
+ return { find: async (instanceId) => (await spec.list()).filter((row) => fields.some((f) => namesInstance(row.formValues[f], instanceId))).map((row) => ({
91378
+ kind: spec.kind,
91379
+ id: row.id,
91380
+ ...row.name !== void 0 ? { name: row.name } : {}
91381
+ })) };
91382
+ }
91383
+ /**
91384
+ * A provider whose `deleteInstance` is refused while anything still uses the instance. The
91385
+ * account is an `integration-instances` kind (D1013), so the refusal lives on the delete the
91386
+ * instances page calls.
91387
+ */
91388
+ function guardInstanceDelete(base, users) {
91389
+ return {
91390
+ ...base,
91391
+ deleteInstance: async (input) => {
91392
+ await assertInstanceUnused(input.id, users());
91393
+ return base.deleteInstance(input);
91394
+ }
91395
+ };
91396
+ }
91118
91397
  //#endregion
91119
91398
  //#region ../../node_modules/xtend/immutable.js
91120
91399
  var require_immutable = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -123159,7 +123438,7 @@ function readOnboardPort(settings) {
123159
123438
  return raw;
123160
123439
  }
123161
123440
  /**
123162
- * Build an onboard {@link BuiltOnboardEntry} from `broker.add` settings.
123441
+ * Build an onboard {@link BuiltOnboardEntry} from the create form's values.
123163
123442
  * Pure — the port is pre-resolved by the caller (auto-allocation is a
123164
123443
  * side-effecting concern kept out of this helper), so the helper performs no
123165
123444
  * I/O of its own.
@@ -123245,7 +123524,7 @@ function resolveStoredPassword(value, legacy) {
123245
123524
  function retiredCiphertextPaths(config) {
123246
123525
  const out = [];
123247
123526
  for (const b of config.brokers) if (b.password?.startsWith("enc:v1:") === true) out.push(`brokers[${b.id}].password`);
123248
- if (config.embeddedPassword.startsWith("enc:v1:")) out.push("embeddedPassword");
123527
+ if (config.embeddedPassword?.startsWith("enc:v1:") === true) out.push("embeddedPassword");
123249
123528
  return out;
123250
123529
  }
123251
123530
  //#endregion
@@ -123279,6 +123558,229 @@ var mqttBrokersEntryKind = defineEntryKind("brokers", {
123279
123558
  writeTrigger: "an operator adds or removes an external MQTT broker entry"
123280
123559
  });
123281
123560
  //#endregion
123561
+ //#region src/mqtt-broker-users.ts
123562
+ /** The addon whose integrations name an MQTT broker, and the field they keep that id in. */
123563
+ var MQTT_HA_ADDON_ID = "provider-mqtt-ha";
123564
+ var MQTT_HA_BROKER_FIELD = "mqttBrokerId";
123565
+ /** The finders for everything that still points at an MQTT broker. */
123566
+ function mqttBrokerUsers(listMqttHaInstances) {
123567
+ return [fieldUserFinder({
123568
+ kind: "integration",
123569
+ field: MQTT_HA_BROKER_FIELD,
123570
+ list: listMqttHaInstances
123571
+ })];
123572
+ }
123573
+ /** MQTT Discovery is installed but has not registered as a provider: not known, NOT absent (D315). */
123574
+ var MqttDiscoveryNotReadyError = class extends Error {
123575
+ constructor() {
123576
+ super("MQTT Discovery is installed but not answering yet (still starting, or switched off), so its integrations cannot be checked: try again once it is running");
123577
+ this.name = "MqttDiscoveryNotReadyError";
123578
+ }
123579
+ };
123580
+ /**
123581
+ * The integrations of the MQTT Discovery addon. Nothing can name a broker only when the registry
123582
+ * ANSWERED that the addon supplies no `integration-instances` AND the addon roster ANSWERED that
123583
+ * it is not installed: then the answer is none. An addon that is installed but has not registered
123584
+ * (booting, switched off) is not-yet-known, and a registry or roster that does not answer, or a
123585
+ * read that fails, is unknown too: all of those throw, so the delete is refused (D49, D315).
123586
+ */
123587
+ async function listMqttHaInstancesOver(api) {
123588
+ const info = await api.capabilities.getCapability.query({ name: "integration-instances" });
123589
+ if (info === null) throw new Error("the capability registry did not answer");
123590
+ if (!info.providers.includes("provider-mqtt-ha")) {
123591
+ if ((await api.addons.list.query()).some((row) => row.manifest.id === "provider-mqtt-ha")) throw new MqttDiscoveryNotReadyError();
123592
+ return [];
123593
+ }
123594
+ return api.integrationInstances.listInstances.query({ addonId: MQTT_HA_ADDON_ID });
123595
+ }
123596
+ //#endregion
123597
+ //#region src/mqtt-broker-instances.ts
123598
+ /**
123599
+ * The MQTT brokers as `integration-instances` (D1013): one instance per `brokers` record. An
123600
+ * external broker is a URL; an ONBOARD broker (`onboard: true` on the create form) is a CamStack
123601
+ * `aedes` server on this hub: the create allocates its port (or honours the operator's) and the
123602
+ * addon spawns it from the record, the delete tears it down. Removing a broker an MQTT Discovery
123603
+ * integration still names is refused (D1012).
123604
+ */
123605
+ var MQTT_INSTANCE_KIND = "mqtt";
123606
+ /** The create-form keys that only mean "run an onboard broker"; the record keeps a descriptor. */
123607
+ var ONBOARD_FORM_KEYS = new Set([
123608
+ "onboard",
123609
+ "port",
123610
+ "allowAnonymous"
123611
+ ]);
123612
+ var PROBE_LABELS = {
123613
+ connected: "Connected",
123614
+ disconnected: "Disconnected",
123615
+ "auth-failed": "Authentication failed",
123616
+ unreachable: "Unreachable",
123617
+ "tls-error": "TLS error"
123618
+ };
123619
+ /** The instance's health word: connected / auth-failed / unreachable / tls-error, latency, clients. */
123620
+ function mqttHealthOf(body, live, now) {
123621
+ if (!isInstanceEnabled(body)) return { status: {
123622
+ state: "off",
123623
+ label: "Switched off"
123624
+ } };
123625
+ if (body.onboard !== void 0) return live.onboard === null ? {
123626
+ status: {
123627
+ state: "error",
123628
+ label: "Not listening"
123629
+ },
123630
+ lastCheckedAt: now
123631
+ } : {
123632
+ status: {
123633
+ state: "ok",
123634
+ label: "Listening",
123635
+ detail: `${live.onboard.connectedClients} connected clients`
123636
+ },
123637
+ lastCheckedAt: now
123638
+ };
123639
+ const probe = live.probe;
123640
+ if (probe === void 0) return { status: {
123641
+ state: "unknown",
123642
+ label: "Not checked yet"
123643
+ } };
123644
+ const detail = probe.status === "connected" ? probe.latencyMs !== null ? `${probe.latencyMs} ms` : void 0 : probe.error;
123645
+ return {
123646
+ status: {
123647
+ state: probe.status === "connected" ? "ok" : "error",
123648
+ label: PROBE_LABELS[probe.status],
123649
+ ...detail !== void 0 ? { detail } : {}
123650
+ },
123651
+ lastCheckedAt: probe.lastCheckedAt
123652
+ };
123653
+ }
123654
+ function withoutOnboardKeys(values) {
123655
+ return Object.fromEntries(Object.entries(values).filter(([key]) => !ONBOARD_FORM_KEYS.has(key)));
123656
+ }
123657
+ function typedText(value) {
123658
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
123659
+ }
123660
+ /** A password the form really typed: not blank, not the redaction token, not the hidden view. */
123661
+ function typedSecret(value) {
123662
+ const text = typedText(value);
123663
+ return text === void 0 || text === "__camstack_redacted__" || isSecretFieldView(text) ? void 0 : text;
123664
+ }
123665
+ function resultOf(probe) {
123666
+ return probe.ok ? {
123667
+ success: true,
123668
+ status: "validated",
123669
+ ...probe.latencyMs !== void 0 ? { latencyMs: probe.latencyMs } : {}
123670
+ } : {
123671
+ success: false,
123672
+ status: "rejected",
123673
+ error: probe.error ?? "The broker did not answer"
123674
+ };
123675
+ }
123676
+ function buildMqttBrokerInstances(records, deps) {
123677
+ const instances = new RecordIntegrationInstances(records, mqttBrokersEntryKind, {
123678
+ description: {
123679
+ role: "services",
123680
+ instanceMode: "multiple",
123681
+ kind: "brokers",
123682
+ canTest: true,
123683
+ kinds: [{
123684
+ id: MQTT_INSTANCE_KIND,
123685
+ label: "MQTT broker",
123686
+ functionCap: "broker",
123687
+ brokerKind: "mqtt",
123688
+ canTest: true
123689
+ }]
123690
+ },
123691
+ formSchema: (id) => deps.formSchema(id, false),
123692
+ kindOf: () => MQTT_INSTANCE_KIND,
123693
+ initialBody: (name) => ({
123694
+ name,
123695
+ url: "mqtt://"
123696
+ }),
123697
+ configured: (body) => body.url.trim().length > 0 && body.url.trim() !== "mqtt://",
123698
+ health: (body, id) => mqttHealthOf(body, deps.liveState(id), Date.now()),
123699
+ onChanged: deps.onChanged,
123700
+ test: async ({ id, values }) => {
123701
+ if (id === null && isOnboardRequested(values)) return {
123702
+ success: true,
123703
+ status: "validated",
123704
+ detail: "A free port is picked when the broker is created"
123705
+ };
123706
+ const saved = id === null ? null : await instances.readResolved(id);
123707
+ if (saved?.body.onboard !== void 0) return deps.onboardListening(saved.id) ? {
123708
+ success: true,
123709
+ status: "validated",
123710
+ detail: `Listening on port ${saved.body.onboard.port}`
123711
+ } : {
123712
+ success: false,
123713
+ status: "rejected",
123714
+ error: "The onboard broker is not listening"
123715
+ };
123716
+ const url = typedText(values["url"]) ?? saved?.body.url;
123717
+ if (url === void 0 || url === "mqtt://") return {
123718
+ success: false,
123719
+ status: "rejected",
123720
+ error: "Enter the broker URL first"
123721
+ };
123722
+ const username = typedText(values["username"]) ?? saved?.body.username;
123723
+ const password = typedSecret(values["password"]) ?? saved?.body.password;
123724
+ return resultOf(await deps.probe({
123725
+ url,
123726
+ ...username !== void 0 ? { username } : {},
123727
+ ...password !== void 0 ? { password } : {}
123728
+ }));
123729
+ }
123730
+ });
123731
+ const base = instances.toProvider();
123732
+ /** Port, descriptor and URL of an onboard broker the form asked for. */
123733
+ const onboardValues = async (id, name, values) => {
123734
+ const built = buildOnboardEntry({
123735
+ id,
123736
+ name,
123737
+ port: readOnboardPort(values) ?? await deps.freePort(),
123738
+ settings: values
123739
+ });
123740
+ return {
123741
+ ...withoutOnboardKeys(values),
123742
+ url: built.url,
123743
+ onboard: built.onboard
123744
+ };
123745
+ };
123746
+ return guardInstanceDelete({
123747
+ ...base,
123748
+ instanceFormSchema: async ({ id }) => {
123749
+ const saved = id === null ? null : await instances.getResolved(id);
123750
+ return deps.formSchema(id, saved?.onboard !== void 0);
123751
+ },
123752
+ createInstance: async (input) => {
123753
+ const values = input.values ?? {};
123754
+ if (!isOnboardRequested(values)) return base.createInstance({
123755
+ ...input,
123756
+ values: withoutOnboardKeys(values)
123757
+ });
123758
+ const id = input.id ?? randomUUID();
123759
+ return base.createInstance({
123760
+ ...input,
123761
+ id,
123762
+ values: await onboardValues(id, input.name, values)
123763
+ });
123764
+ },
123765
+ updateInstance: async (input) => {
123766
+ if (!isOnboardRequested(input.values)) return base.updateInstance({
123767
+ ...input,
123768
+ values: withoutOnboardKeys(input.values)
123769
+ });
123770
+ const current = await instances.getResolved(input.id);
123771
+ if (current === null) throw new Error(`mqtt-broker: broker '${input.id}' not found`);
123772
+ if (current.onboard !== void 0) return base.updateInstance({
123773
+ ...input,
123774
+ values: withoutOnboardKeys(input.values)
123775
+ });
123776
+ return base.updateInstance({
123777
+ ...input,
123778
+ values: await onboardValues(input.id, input.name ?? current.name, input.values)
123779
+ });
123780
+ }
123781
+ }, () => mqttBrokerUsers(deps.listMqttHaInstances));
123782
+ }
123783
+ //#endregion
123282
123784
  //#region src/migrations/brokers-to-records.ts
123283
123785
  /**
123284
123786
  * The external MQTT brokers live in the `brokers` records (D985, D996); the old addon-settings
@@ -123368,46 +123870,163 @@ async function planDropBrokersKey(ports) {
123368
123870
  }] };
123369
123871
  }
123370
123872
  //#endregion
123873
+ //#region src/migrations/embedded-to-onboard.ts
123874
+ /**
123875
+ * The legacy single embedded broker lived in FLAT addon-settings keys (`embeddedEnabled`,
123876
+ * `embeddedPort`, ...). It is an ONBOARD broker record now, so the instance list, the pickers,
123877
+ * the test and the delete all see it (D1013). Two migrations of the catalogue, in this order:
123878
+ *
123879
+ * 1. `embeddedToOnboardRecord` (procedure): a legacy broker (a stopped one as a switched-off
123880
+ * record) becomes a `brokers` record
123881
+ * under the SAME id (`embeddedId`, else the `'embedded'` id the old code derived), so a
123882
+ * consumer that stored that id still resolves. It never overwrites a record of that id.
123883
+ * 2. `planDropEmbeddedKeys` (plan): the flat keys are deleted from the canonical
123884
+ * `addon-settings` rows, and only while the record that replaces them exists and carries the
123885
+ * password the legacy key held. `embeddedClients` / `embeddedAcl` are not flat broker keys
123886
+ * and stay.
123887
+ */
123888
+ /** The flat keys that described the legacy embedded broker. */
123889
+ var LEGACY_EMBEDDED_KEYS = [
123890
+ "embeddedEnabled",
123891
+ "embeddedId",
123892
+ "embeddedPort",
123893
+ "embeddedAllowAnonymous",
123894
+ "embeddedUsername",
123895
+ "embeddedPassword"
123896
+ ];
123897
+ var LEGACY_EMBEDDED_NAME = "Embedded broker";
123898
+ function onboardBodyOf(legacy) {
123899
+ return {
123900
+ name: LEGACY_EMBEDDED_NAME,
123901
+ url: `mqtt://127.0.0.1:${legacy.port}`,
123902
+ ...legacy.username !== void 0 ? { username: legacy.username } : {},
123903
+ ...legacy.password !== void 0 ? { password: legacy.password } : {},
123904
+ onboard: {
123905
+ port: legacy.port,
123906
+ allowAnonymous: legacy.allowAnonymous
123907
+ },
123908
+ ...legacy.enabled ? {} : { enabled: false }
123909
+ };
123910
+ }
123911
+ async function embeddedToOnboardRecord(ports) {
123912
+ const legacy = await ports.readLegacyEmbedded();
123913
+ if (legacy === null) return {
123914
+ outcome: "already-done",
123915
+ summary: { migrated: 0 }
123916
+ };
123917
+ if ((await ports.readRecords()).has(legacy.id)) return {
123918
+ outcome: "already-done",
123919
+ summary: { migrated: 0 }
123920
+ };
123921
+ await ports.putOnboardRecord(legacy.id, onboardBodyOf(legacy));
123922
+ return {
123923
+ outcome: "done",
123924
+ summary: { migrated: 1 }
123925
+ };
123926
+ }
123927
+ async function planDropEmbeddedKeys(ports) {
123928
+ const raw = await ports.readRawEmbeddedKeys();
123929
+ const present = LEGACY_EMBEDDED_KEYS.filter((key) => key in raw);
123930
+ if (present.length === 0) return { edits: [] };
123931
+ const refuse = (reason) => {
123932
+ ports.warn(`mqtt-broker migration: the legacy embedded keys are kept: ${reason}`);
123933
+ throw new Error(`the legacy embedded broker keys are not deleted: ${reason}`);
123934
+ };
123935
+ const legacy = await ports.readLegacyEmbedded();
123936
+ if (legacy !== null) {
123937
+ const record = (await ports.readRecords()).get(legacy.id);
123938
+ if (record === void 0) return refuse(`the record '${legacy.id}' does not exist`);
123939
+ if ((legacy.password ?? "").length > 0 && !record.hasPassword) return refuse(`the record '${legacy.id}' holds no password`);
123940
+ }
123941
+ return { edits: [{
123942
+ op: "deleteKeys",
123943
+ scope: ADDON_SETTINGS_TABLE,
123944
+ keys: present.map((key) => `${MQTT_BROKER_ADDON_ID}.${key}`),
123945
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [`${MQTT_BROKER_ADDON_ID}.${key}`, {
123946
+ addonId: MQTT_BROKER_ADDON_ID,
123947
+ key,
123948
+ value: raw[key]
123949
+ }])))
123950
+ }] };
123951
+ }
123952
+ //#endregion
123371
123953
  //#region src/migrations/index.ts
123372
123954
  var BROKERS_TO_RECORDS_ID = "mqtt-broker/2026-11-03-brokers-settings-to-records";
123373
123955
  var DROP_BROKERS_KEY_ID = "mqtt-broker/2026-11-03-drop-brokers-key";
123956
+ var EMBEDDED_TO_ONBOARD_ID = "mqtt-broker/2026-11-05-embedded-broker-to-onboard-record";
123957
+ var DROP_EMBEDDED_KEYS_ID = "mqtt-broker/2026-11-05-drop-embedded-keys";
123374
123958
  var FIXTURE_MARK = "a setting key the migration does not know";
123375
123959
  /**
123376
123960
  * The `mqtt-broker` catalogue (D987), offered to the engine when the addon initialises. Both
123377
123961
  * entries are `tolerate`: the embedded broker and every record keep working while a legacy key
123378
123962
  * stays where it is.
123379
123963
  */
123380
- var ADDON_MIGRATIONS = [{
123381
- meta: {
123382
- id: BROKERS_TO_RECORDS_ID,
123383
- owner: "mqtt-broker",
123384
- level: "addon-state",
123385
- seq: 1,
123386
- dependsOn: [],
123387
- store: "settings",
123388
- scope: "cluster",
123389
- onFailure: "tolerate",
123390
- bodyKind: "procedure",
123391
- description: "Check that every external broker of the old settings list is a brokers record; never deletes",
123392
- fixtureMark: FIXTURE_MARK
123393
- },
123394
- procedure: verifyBrokersAreRecords
123395
- }, {
123396
- meta: {
123397
- id: DROP_BROKERS_KEY_ID,
123398
- owner: "mqtt-broker",
123399
- level: "addon-state",
123400
- seq: 2,
123401
- dependsOn: [BROKERS_TO_RECORDS_ID],
123402
- store: "settings",
123403
- scope: "cluster",
123404
- onFailure: "tolerate",
123405
- bodyKind: "plan",
123406
- description: "Delete the legacy brokers settings key once every broker is a record",
123407
- fixtureMark: FIXTURE_MARK
123408
- },
123409
- plan: planDropBrokersKey
123410
- }];
123964
+ var ADDON_MIGRATIONS = [
123965
+ {
123966
+ meta: {
123967
+ id: BROKERS_TO_RECORDS_ID,
123968
+ owner: "mqtt-broker",
123969
+ level: "addon-state",
123970
+ seq: 1,
123971
+ dependsOn: [],
123972
+ store: "settings",
123973
+ scope: "cluster",
123974
+ onFailure: "tolerate",
123975
+ bodyKind: "procedure",
123976
+ description: "Check that every external broker of the old settings list is a brokers record; never deletes",
123977
+ fixtureMark: FIXTURE_MARK
123978
+ },
123979
+ procedure: verifyBrokersAreRecords
123980
+ },
123981
+ {
123982
+ meta: {
123983
+ id: DROP_BROKERS_KEY_ID,
123984
+ owner: "mqtt-broker",
123985
+ level: "addon-state",
123986
+ seq: 2,
123987
+ dependsOn: [BROKERS_TO_RECORDS_ID],
123988
+ store: "settings",
123989
+ scope: "cluster",
123990
+ onFailure: "tolerate",
123991
+ bodyKind: "plan",
123992
+ description: "Delete the legacy brokers settings key once every broker is a record",
123993
+ fixtureMark: FIXTURE_MARK
123994
+ },
123995
+ plan: planDropBrokersKey
123996
+ },
123997
+ {
123998
+ meta: {
123999
+ id: EMBEDDED_TO_ONBOARD_ID,
124000
+ owner: "mqtt-broker",
124001
+ level: "addon-state",
124002
+ seq: 3,
124003
+ dependsOn: [DROP_BROKERS_KEY_ID],
124004
+ store: "settings",
124005
+ scope: "cluster",
124006
+ onFailure: "tolerate",
124007
+ bodyKind: "procedure",
124008
+ description: "The legacy embedded broker (flat embedded* keys) becomes an onboard brokers record under the same id; never overwrites a record",
124009
+ fixtureMark: FIXTURE_MARK
124010
+ },
124011
+ procedure: embeddedToOnboardRecord
124012
+ },
124013
+ {
124014
+ meta: {
124015
+ id: DROP_EMBEDDED_KEYS_ID,
124016
+ owner: "mqtt-broker",
124017
+ level: "addon-state",
124018
+ seq: 4,
124019
+ dependsOn: [EMBEDDED_TO_ONBOARD_ID],
124020
+ store: "settings",
124021
+ scope: "cluster",
124022
+ onFailure: "tolerate",
124023
+ bodyKind: "plan",
124024
+ description: "Delete the flat embedded broker keys once the onboard record holds them",
124025
+ fixtureMark: FIXTURE_MARK
124026
+ },
124027
+ plan: planDropEmbeddedKeys
124028
+ }
124029
+ ];
123411
124030
  //#endregion
123412
124031
  //#region src/mqtt-entry-record-kinds.ts
123413
124032
  var aclAccessSchema = _enum([
@@ -123615,123 +124234,25 @@ var MqttAclStore = class MqttAclStore {
123615
124234
  *
123616
124235
  * Lifecycle:
123617
124236
  * - External broker entries are persisted in `this.activeExternalBrokers`.
123618
- * - The embedded broker is persisted as flat `embedded*` config keys
123619
- * (`embeddedEnabled`, `embeddedPort`, …) so the standard settings
123620
- * form can drive it; {@link MqttBrokerAddon.deriveEmbeddedEntry}
123621
- * reassembles them into an `EmbeddedBrokerEntry`.
123622
- * - On boot we start the embedded broker when `embeddedEnabled`.
123623
- * - `addBroker` / `removeBroker` / `startEmbeddedBroker` /
123624
- * `stopEmbeddedBroker` mutate the config and the runtime state.
124237
+ * - The legacy single embedded broker is an onboard `brokers` record (migrated from the flat
124238
+ * `embedded*` keys, same id); `startEmbeddedBroker` / `stopEmbeddedBroker` act on that record.
124239
+ * - `addBroker` / `removeBroker` mutate the records and the runtime state.
123625
124240
  * - `testConnection` does a one-shot `mqtt.connect` race against a 3s
123626
124241
  * timeout AND refreshes the probe cache for the broker.
123627
124242
  */
123628
124243
  /** bcrypt cost factor — exported for tests. */
123629
124244
  var MQTT_EMBEDDED_BCRYPT_ROUNDS = 10;
123630
124245
  var PROBE_INTERVAL_MS = 3e4;
123631
- var DEFAULT_EMBEDDED_PORT = 1883;
123632
- /**
123633
- * Per-kind broker creation form for kind='mqtt', rendered by the unified
123634
- * Broker manager / create picker (via `broker.getSettingsSchema`). PURE
123635
- * DATA — emits the flat `{ url, username, password, clientIdPrefix }`
123636
- * shape `broker.add`'s `settings` payload consumes. Mirrors the external
123637
- * broker fields `addBroker` accepts.
123638
- */
123639
- var mqttBrokerSettingsSchema = { sections: [{
123640
- id: "mqtt-broker-connection",
123641
- title: "MQTT connection",
123642
- titleKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.title",
123643
- columns: 1,
123644
- fields: [
123645
- {
123646
- type: "boolean",
123647
- key: "onboard",
123648
- label: "Run an onboard broker",
123649
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.onboard.label",
123650
- description: "Spin up a CamStack-hosted aedes broker on this hub instead of connecting to an external one. Each onboard broker gets its own dedicated server + port.",
123651
- descriptionKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.onboard.description",
123652
- default: false
123653
- },
123654
- {
123655
- type: "number",
123656
- key: "port",
123657
- label: "Port",
123658
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.port.label",
123659
- placeholder: "(auto)",
123660
- description: "TCP port for the onboard broker. Leave blank to auto-allocate a free port.",
123661
- descriptionKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.port.description",
123662
- showWhen: {
123663
- field: "onboard",
123664
- equals: true
123665
- }
123666
- },
123667
- {
123668
- type: "boolean",
123669
- key: "allowAnonymous",
123670
- label: "Allow anonymous",
123671
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.allowAnonymous.label",
123672
- description: "Permit clients to connect without a username/password.",
123673
- descriptionKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.allowAnonymous.description",
123674
- default: false,
123675
- showWhen: {
123676
- field: "onboard",
123677
- equals: true
123678
- }
123679
- },
123680
- {
123681
- type: "text",
123682
- key: "url",
123683
- label: "Broker URL",
123684
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.url.label",
123685
- placeholder: "mqtt://localhost:1883",
123686
- showWhen: {
123687
- field: "onboard",
123688
- equals: false
123689
- }
123690
- },
123691
- {
123692
- type: "text",
123693
- key: "username",
123694
- label: "Username",
123695
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.username.label",
123696
- placeholder: "(optional)"
123697
- },
123698
- {
123699
- type: "password",
123700
- key: "password",
123701
- label: "Password",
123702
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.password.label",
123703
- showToggle: true
123704
- },
123705
- {
123706
- type: "text",
123707
- key: "clientIdPrefix",
123708
- label: "Client ID prefix",
123709
- labelKey: "mqtt-broker:mqttBrokerSettings.s_mqtt-broker-connection.clientIdPrefix.label",
123710
- placeholder: "(optional)",
123711
- showWhen: {
123712
- field: "onboard",
123713
- equals: false
123714
- }
123715
- }
123716
- ]
123717
- }] };
123718
124246
  var DEFAULT_CONFIG = {
123719
- embeddedEnabled: false,
123720
- embeddedId: "",
123721
- embeddedPort: DEFAULT_EMBEDDED_PORT,
123722
- embeddedAllowAnonymous: false,
123723
- embeddedUsername: "",
123724
- embeddedPassword: "",
123725
124247
  embeddedClients: [],
123726
124248
  embeddedAcl: []
123727
124249
  };
123728
124250
  var MqttBrokerAddon = class extends BaseAddon {
123729
- embeddedRuntime = null;
123730
- /** Per-entry onboard `aedes` runtimes, keyed by `ExternalBrokerEntry.id`. */
124251
+ /** Per-record onboard `aedes` runtimes, keyed by `ExternalBrokerEntry.id`. */
123731
124252
  onboardRuntimes = /* @__PURE__ */ new Map();
123732
124253
  probeCache = null;
123733
124254
  brokerStore = null;
123734
- instances = null;
124255
+ brokerInstances = null;
123735
124256
  clientStore = null;
123736
124257
  aclStore = null;
123737
124258
  /** The external broker rows: the `brokers` records, secrets resolved. */
@@ -123745,6 +124266,20 @@ var MqttBrokerAddon = class extends BaseAddon {
123745
124266
  if (this.brokerStore === null) throw new Error("mqtt-broker: the broker records are not open");
123746
124267
  return this.brokerStore;
123747
124268
  }
124269
+ /** What the addon knows of a broker right now: its onboard server or its last probe. */
124270
+ liveState(id) {
124271
+ const running = this.onboardRuntimes.get(id);
124272
+ const probe = this.probeCache?.get(id);
124273
+ return {
124274
+ onboard: running === void 0 ? null : { connectedClients: running.aedes.connectedClients },
124275
+ ...probe !== void 0 ? { probe: {
124276
+ status: probe.status,
124277
+ latencyMs: probe.latencyMs,
124278
+ ...probe.error !== void 0 ? { error: probe.error } : {},
124279
+ lastCheckedAt: probe.lastCheckedAt
124280
+ } } : {}
124281
+ };
124282
+ }
123748
124283
  async persistExternalBrokers(entries) {
123749
124284
  this.activeExternalBrokers = [...entries];
123750
124285
  await this.requireBrokerStore().replaceAll(entries);
@@ -123794,19 +124329,13 @@ var MqttBrokerAddon = class extends BaseAddon {
123794
124329
  this.brokerStore = MqttBrokerStore.of(records);
123795
124330
  this.clientStore = MqttClientStore.of(records);
123796
124331
  this.aclStore = MqttAclStore.of(records);
123797
- this.instances = new RecordIntegrationInstances(records, mqttBrokersEntryKind, {
123798
- description: {
123799
- role: "services",
123800
- instanceMode: "multiple",
123801
- kind: "brokers",
123802
- canTest: false
123803
- },
123804
- formSchema: () => this.brokerForm(),
123805
- initialBody: (name) => ({
123806
- name,
123807
- url: "mqtt://"
123808
- }),
123809
- configured: (body) => body.url.trim().length > 0 && body.url.trim() !== "mqtt://",
124332
+ this.brokerInstances = buildMqttBrokerInstances(records, {
124333
+ formSchema: (id, onboard) => this.brokerForm(id, onboard),
124334
+ listMqttHaInstances: () => listMqttHaInstancesOver(this.ctx.api),
124335
+ freePort: () => findFreePort(),
124336
+ probe: (cfg) => this.probeMqtt(cfg),
124337
+ onboardListening: (id) => this.onboardRuntimes.has(id),
124338
+ liveState: (id) => this.liveState(id),
123810
124339
  onChanged: async () => {
123811
124340
  await this.refreshExternalBrokers();
123812
124341
  }
@@ -123835,29 +124364,9 @@ var MqttBrokerAddon = class extends BaseAddon {
123835
124364
  });
123836
124365
  this.probeCache.setBrokersSource(() => this.collectExternalProbeInputs());
123837
124366
  this.probeCache.start();
123838
- const persistedEmbedded = this.deriveEmbeddedEntry();
123839
- if (persistedEmbedded) try {
123840
- await this.spawnEmbedded(persistedEmbedded);
123841
- this.ctx.logger.info("embedded mqtt broker restarted", {
123842
- meta: { port: persistedEmbedded.port },
123843
- tags: {
123844
- topic: "mqtt-broker",
123845
- phase: "embedded-restarted"
123846
- }
123847
- });
123848
- } catch (err) {
123849
- this.ctx.logger.warn("embedded mqtt broker failed to restart", {
123850
- meta: { error: errMsg(err) },
123851
- tags: {
123852
- topic: "mqtt-broker",
123853
- phase: "embedded-restart-failed"
123854
- }
123855
- });
123856
- }
123857
124367
  await this.reconcileOnboardRuntimes();
123858
124368
  this.ctx.addDisposer(async () => {
123859
124369
  await this.probeCache?.stop();
123860
- await this.shutdownEmbedded().catch(() => void 0);
123861
124370
  await this.shutdownAllOnboard();
123862
124371
  });
123863
124372
  const provider = {
@@ -123869,11 +124378,13 @@ var MqttBrokerAddon = class extends BaseAddon {
123869
124378
  startEmbeddedBroker: async (input) => this.startEmbeddedBroker(input),
123870
124379
  stopEmbeddedBroker: async ({ id }) => this.stopEmbeddedBroker(id),
123871
124380
  getStatus: async () => ({
123872
- brokerCount: this.activeExternalBrokers.length + (this.config.embeddedEnabled ? 1 : 0),
123873
- embeddedRunning: this.embeddedRuntime !== null
124381
+ brokerCount: this.activeExternalBrokers.length,
124382
+ embeddedRunning: this.onboardRuntimes.size > 0
123874
124383
  })
123875
124384
  };
123876
124385
  const unifiedProvider = this.buildUnifiedBrokerProvider();
124386
+ const brokerInstances = this.brokerInstances;
124387
+ if (brokerInstances === null) throw new Error("mqtt-broker: the broker instances are not built");
123877
124388
  return [
123878
124389
  {
123879
124390
  capability: mqttBrokerCapability,
@@ -123885,111 +124396,21 @@ var MqttBrokerAddon = class extends BaseAddon {
123885
124396
  },
123886
124397
  {
123887
124398
  capability: integrationInstancesCapability,
123888
- provider: this.instances.toProvider()
124399
+ provider: brokerInstances
123889
124400
  }
123890
124401
  ];
123891
124402
  }
124403
+ /**
124404
+ * The bus-only `broker` cap (D1013). The brokers themselves are the `integration-instances`
124405
+ * provider; this one only answers the config read and the status.
124406
+ */
123892
124407
  buildUnifiedBrokerProvider() {
123893
- const KIND = "mqtt";
123894
- const ownerAddonId = this.ctx.id;
123895
- const adapt = (info) => ({
123896
- id: info.id,
123897
- addonId: ownerAddonId,
123898
- name: info.name,
123899
- kind: KIND,
123900
- status: mapMqttStatus(info.status),
123901
- info: {
123902
- ...info.latencyMs !== null ? { latencyMs: info.latencyMs } : {},
123903
- ...info.kind === "embedded" ? {
123904
- embedded: true,
123905
- connectedClients: info.connectedClients ?? 0
123906
- } : {}
123907
- },
123908
- lastCheckedAt: info.lastCheckedAt ?? null,
123909
- error: info.error ?? null
123910
- });
123911
- const owns = (id) => {
123912
- if (this.activeExternalBrokers.some((b) => b.id === id)) return true;
123913
- const embedded = this.deriveEmbeddedEntry();
123914
- return embedded !== null && embedded.id === id;
123915
- };
124408
+ const owns = (id) => this.activeExternalBrokers.some((b) => b.id === id);
123916
124409
  return {
123917
- list: async ({ kind }) => {
123918
- if (kind && kind !== KIND) return [];
123919
- return (await this.listBrokers()).map(adapt);
123920
- },
123921
- get: async ({ id }) => {
123922
- const match = (await this.listBrokers()).find((b) => b.id === id);
123923
- return match ? adapt(match) : null;
123924
- },
123925
- listProviders: async () => [{
123926
- addonId: ownerAddonId,
123927
- kinds: [{
123928
- kind: KIND,
123929
- label: "MQTT"
123930
- }]
123931
- }],
123932
- add: async ({ kind, name, settings, id }) => {
123933
- if (kind !== KIND) throw new Error(`mqtt-broker: only kind '${KIND}' is handled here (got '${kind}')`);
123934
- if (id !== void 0) throw new Error("mqtt-broker: adopting an existing broker id is not supported by this provider");
123935
- if (isOnboardRequested(settings)) return this.addOnboardBroker(name, settings);
123936
- const url = typeof settings["url"] === "string" ? settings["url"] : "";
123937
- if (!url) throw new Error("mqtt-broker.add: settings.url is required");
123938
- const input = {
123939
- name,
123940
- url,
123941
- ...typeof settings["username"] === "string" ? { username: settings["username"] } : {},
123942
- ...typeof settings["password"] === "string" ? { password: settings["password"] } : {},
123943
- ...typeof settings["clientIdPrefix"] === "string" ? { clientIdPrefix: settings["clientIdPrefix"] } : {}
123944
- };
123945
- return this.addBroker(input);
123946
- },
123947
- remove: async ({ id }) => {
123948
- if (!owns(id)) return;
123949
- await this.removeBroker(id);
123950
- },
123951
- testConnection: async ({ id }) => {
123952
- if (!owns(id)) return {
123953
- ok: false,
123954
- error: "unknown broker"
123955
- };
123956
- return this.testConnection(id);
123957
- },
123958
- getSettings: async ({ id }) => {
123959
- if (!owns(id)) return null;
123960
- return this.getBrokerConfig(id);
123961
- },
123962
- setSettings: async () => {
123963
- throw new Error("mqtt-broker.setSettings: not supported — use remove + add to replace a broker");
123964
- },
123965
124410
  getBrokerConfig: async ({ id }) => {
123966
124411
  if (!owns(id)) return null;
123967
124412
  return this.getBrokerConfig(id);
123968
124413
  },
123969
- getSettingsSchema: async ({ kind }) => {
123970
- if (kind !== KIND) return null;
123971
- return mqttBrokerSettingsSchema;
123972
- },
123973
- testSettings: async ({ kind, settings }) => {
123974
- if (kind !== KIND) return {
123975
- ok: false,
123976
- error: `unsupported kind: ${kind}`
123977
- };
123978
- if (isOnboardRequested(settings)) return {
123979
- ok: true,
123980
- latencyMs: 0
123981
- };
123982
- const url = typeof settings["url"] === "string" ? settings["url"] : "";
123983
- if (!url) return {
123984
- ok: false,
123985
- error: "settings.url is required"
123986
- };
123987
- return this.probeMqtt({
123988
- url,
123989
- ...typeof settings["username"] === "string" ? { username: settings["username"] } : {},
123990
- ...typeof settings["password"] === "string" ? { password: settings["password"] } : {}
123991
- });
123992
- },
123993
124414
  publish: async () => {
123994
124415
  throw new Error("mqtt-broker.publish: not supported — fetch getBrokerConfig + open your own mqtt.js client (see \"NOT a pub/sub proxy\" in mqtt-broker.cap.ts)");
123995
124416
  },
@@ -124003,7 +124424,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124003
124424
  getStatus: async () => {
124004
124425
  const all = await this.listBrokers();
124005
124426
  return {
124006
- brokerCount: this.activeExternalBrokers.length + (this.config.embeddedEnabled ? 1 : 0),
124427
+ brokerCount: this.activeExternalBrokers.length,
124007
124428
  connectedCount: all.filter((b) => b.status === "connected").length
124008
124429
  };
124009
124430
  }
@@ -124011,35 +124432,13 @@ var MqttBrokerAddon = class extends BaseAddon {
124011
124432
  }
124012
124433
  async onShutdown() {
124013
124434
  await this.probeCache?.stop();
124014
- await this.shutdownEmbedded().catch(() => void 0);
124015
124435
  await this.shutdownAllOnboard();
124016
124436
  }
124017
124437
  async onConfigChanged() {
124018
124438
  this.activeExternalBrokers = await this.requireBrokerStore().listResolved();
124019
124439
  await this.syncEmbeddedEntriesFromConfig();
124020
124440
  await this.reconcileOnboardRuntimes();
124021
- const desired = this.deriveEmbeddedEntry();
124022
- const running = this.embeddedRuntime?.entry ?? null;
124023
- if (!desired && running) {
124024
- await this.shutdownEmbedded();
124025
- return;
124026
- }
124027
- if (desired && !running) {
124028
- await this.spawnEmbedded(desired).catch((err) => {
124029
- this.ctx.logger.warn("embedded mqtt broker spawn (on config change) failed", { meta: { error: errMsg(err) } });
124030
- });
124031
- return;
124032
- }
124033
- if (desired && running) {
124034
- if (requiresEmbeddedRespawn(desired, running)) {
124035
- await this.shutdownEmbedded();
124036
- await this.spawnEmbedded(desired).catch((err) => {
124037
- this.ctx.logger.warn("embedded mqtt broker respawn failed", { meta: { error: errMsg(err) } });
124038
- });
124039
- return;
124040
- }
124041
- this.reconcileEmbeddedClients();
124042
- }
124441
+ this.reconcileEmbeddedClients();
124043
124442
  }
124044
124443
  async listBrokers() {
124045
124444
  const out = [];
@@ -124073,28 +124472,12 @@ var MqttBrokerAddon = class extends BaseAddon {
124073
124472
  };
124074
124473
  out.push(info);
124075
124474
  }
124076
- const embedded = this.deriveEmbeddedEntry();
124077
- if (embedded) {
124078
- const running = this.embeddedRuntime;
124079
- const status = running !== null ? "connected" : "disconnected";
124080
- const info = {
124081
- id: embedded.id,
124082
- name: embedded.name,
124083
- url: `mqtt://127.0.0.1:${embedded.port}`,
124084
- kind: "embedded",
124085
- status,
124086
- latencyMs: null,
124087
- ...running ? { connectedClients: running.aedes.connectedClients } : {},
124088
- lastCheckedAt: Date.now()
124089
- };
124090
- out.push(info);
124091
- }
124092
124475
  return out;
124093
124476
  }
124094
124477
  getBrokerConfig(id) {
124095
124478
  const external = this.activeExternalBrokers.find((b) => b.id === id);
124096
124479
  if (external) {
124097
- if (external.enabled === false) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124480
+ if (!isInstanceEnabled(external)) throw new Error(`mqtt-broker: broker '${id}' is switched off`);
124098
124481
  const password = this.storedPassword(external.password);
124099
124482
  return {
124100
124483
  url: external.url,
@@ -124103,15 +124486,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124103
124486
  ...external.clientIdPrefix !== void 0 ? { clientIdPrefix: external.clientIdPrefix } : {}
124104
124487
  };
124105
124488
  }
124106
- const embedded = this.deriveEmbeddedEntry();
124107
- if (embedded && embedded.id === id) {
124108
- const password = this.storedPassword(embedded.password);
124109
- return {
124110
- url: `mqtt://127.0.0.1:${embedded.port}`,
124111
- ...embedded.username !== void 0 ? { username: embedded.username } : {},
124112
- ...password !== void 0 ? { password } : {}
124113
- };
124114
- }
124115
124489
  throw new Error(`mqtt-broker: broker '${id}' not found`);
124116
124490
  }
124117
124491
  async addBroker(input) {
@@ -124132,44 +124506,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124132
124506
  } });
124133
124507
  return { id };
124134
124508
  }
124135
- /**
124136
- * Create a per-entry ONBOARD broker from `broker.add` settings: allocate
124137
- * (or honour) a port, persist an `ExternalBrokerEntry` carrying an
124138
- * `onboard` descriptor, then spawn its dedicated `aedes` server.
124139
- */
124140
- async addOnboardBroker(name, settings) {
124141
- const id = randomUUID();
124142
- const port = readOnboardPort(settings) ?? await findFreePort();
124143
- const built = buildOnboardEntry({
124144
- id,
124145
- name,
124146
- port,
124147
- settings
124148
- });
124149
- const entry = {
124150
- id: built.id,
124151
- name: built.name,
124152
- url: built.url,
124153
- ...built.username !== void 0 ? { username: built.username } : {},
124154
- ...built.password !== void 0 ? { password: built.password } : {},
124155
- onboard: built.onboard
124156
- };
124157
- const next = [...this.activeExternalBrokers, entry];
124158
- await this.persistExternalBrokers(next);
124159
- const spawn = this.onboardSpawnEntry(entry);
124160
- if (spawn) await this.spawnOnboard(spawn);
124161
- this.ctx.logger.info("onboard mqtt broker added", {
124162
- meta: {
124163
- id,
124164
- port
124165
- },
124166
- tags: {
124167
- topic: "mqtt-broker",
124168
- phase: "onboard-started"
124169
- }
124170
- });
124171
- return { id };
124172
- }
124173
124509
  async removeBroker(id) {
124174
124510
  const removed = this.activeExternalBrokers.find((b) => b.id === id);
124175
124511
  if (removed) {
@@ -124180,13 +124516,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124180
124516
  this.ctx.logger.info("mqtt broker removed", { meta: { id } });
124181
124517
  return;
124182
124518
  }
124183
- const embedded = this.deriveEmbeddedEntry();
124184
- if (embedded && embedded.id === id) {
124185
- await this.shutdownEmbedded();
124186
- await this.updateGlobalSettings({ embeddedEnabled: false });
124187
- this.ctx.logger.info("embedded mqtt broker removed", { meta: { id } });
124188
- return;
124189
- }
124190
124519
  }
124191
124520
  async testConnection(id) {
124192
124521
  let cfg;
@@ -124205,7 +124534,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124205
124534
  * One-shot connectivity probe against an MQTT endpoint built from a
124206
124535
  * flat config (`{url, username?, password?}`). Shared by the
124207
124536
  * id-keyed `testConnection` (existing broker) and the pre-creation
124208
- * `testSettings` (throwaway settings the operator hasn't saved yet).
124537
+ * the instance test (`testInstance`) of a broker not saved yet (the typed values).
124209
124538
  * Never throws — every failure resolves to `{ ok: false, error }`.
124210
124539
  */
124211
124540
  async probeMqtt(cfg) {
@@ -124250,30 +124579,46 @@ var MqttBrokerAddon = class extends BaseAddon {
124250
124579
  });
124251
124580
  });
124252
124581
  }
124582
+ /** The `brokers` records, for the two legacy cap methods that create or switch off one. */
124583
+ brokerRecordHandle() {
124584
+ const handle = this.ctx.records?.kind(mqttBrokersEntryKind);
124585
+ if (handle === void 0) throw new Error("mqtt-broker: the broker records are not open");
124586
+ return handle;
124587
+ }
124588
+ /** Create an ONBOARD broker record; the reconcile then spawns its `aedes` server. */
124253
124589
  async startEmbeddedBroker(input) {
124254
- if (this.embeddedRuntime) throw new Error("embedded broker already running — call stopEmbeddedBroker first");
124255
- const id = this.config.embeddedId || randomUUID();
124256
- const entry = {
124590
+ const id = randomUUID();
124591
+ const built = buildOnboardEntry({
124257
124592
  id,
124258
- name: "Embedded broker",
124593
+ name: LEGACY_EMBEDDED_NAME,
124259
124594
  port: input.port,
124260
- allowAnonymous: input.allowAnonymous,
124261
- ...input.username !== void 0 ? { username: input.username } : {},
124262
- ...input.password !== void 0 ? { password: input.password } : {}
124263
- };
124264
- await this.spawnEmbedded(entry);
124265
- await this.updateGlobalSettings({
124266
- embeddedEnabled: true,
124267
- embeddedId: id,
124268
- embeddedPort: input.port,
124269
- embeddedAllowAnonymous: input.allowAnonymous,
124270
- embeddedUsername: input.username ?? "",
124271
- embeddedPassword: input.password ?? ""
124595
+ settings: {
124596
+ allowAnonymous: input.allowAnonymous,
124597
+ ...input.username !== void 0 ? { username: input.username } : {},
124598
+ ...input.password !== void 0 ? { password: input.password } : {}
124599
+ }
124272
124600
  });
124601
+ const handle = this.brokerRecordHandle();
124602
+ await handle.put({
124603
+ id,
124604
+ data: mqttBrokersEntryKind.schema.parse({
124605
+ name: built.name,
124606
+ url: built.url,
124607
+ ...built.username !== void 0 ? { username: built.username } : {},
124608
+ ...built.password !== void 0 ? { password: built.password } : {},
124609
+ onboard: built.onboard
124610
+ })
124611
+ }, { ifRev: 0 });
124612
+ await this.refreshExternalBrokers();
124613
+ if (!this.onboardRuntimes.has(id)) {
124614
+ await handle.delete(id);
124615
+ await this.refreshExternalBrokers();
124616
+ throw new Error(`embedded broker could not listen on port ${input.port}`);
124617
+ }
124273
124618
  this.ctx.logger.info("embedded mqtt broker started", {
124274
124619
  meta: {
124275
124620
  id,
124276
- port: entry.port
124621
+ port: input.port
124277
124622
  },
124278
124623
  tags: {
124279
124624
  topic: "mqtt-broker",
@@ -124295,20 +124640,22 @@ var MqttBrokerAddon = class extends BaseAddon {
124295
124640
  });
124296
124641
  return {
124297
124642
  id,
124298
- url: `mqtt://127.0.0.1:${entry.port}`
124643
+ url: built.url
124299
124644
  };
124300
124645
  }
124646
+ /** Switch an onboard broker off (its record stays, so it can be switched on again). */
124301
124647
  async stopEmbeddedBroker(id) {
124302
- if (!this.embeddedRuntime || this.embeddedRuntime.entry.id !== id) return;
124303
- await this.shutdownEmbedded();
124304
- await this.updateGlobalSettings({ embeddedEnabled: false });
124648
+ const handle = this.brokerRecordHandle();
124649
+ const row = await handle.get(id);
124650
+ if (row === null || row.data.onboard === void 0) return;
124651
+ await handle.patch(id, { enabled: false });
124652
+ await this.refreshExternalBrokers();
124305
124653
  this.ctx.logger.info("embedded mqtt broker stopped", { meta: { id } });
124306
124654
  }
124307
124655
  /**
124308
124656
  * Build + listen an `aedes` server for `entry` and RETURN the runtime
124309
- * without assigning it to any field. Shared by the legacy single
124310
- * embedded broker ({@link spawnEmbedded}) and the per-entry onboard
124311
- * brokers ({@link spawnOnboard}).
124657
+ * without assigning it to any field (the onboard brokers keep theirs in
124658
+ * {@link spawnOnboard}).
124312
124659
  */
124313
124660
  async spawnAedes(entry) {
124314
124661
  const aedes = new import_aedes.default();
@@ -124347,15 +124694,6 @@ var MqttBrokerAddon = class extends BaseAddon {
124347
124694
  aedes.close(() => resolve());
124348
124695
  });
124349
124696
  }
124350
- async spawnEmbedded(entry) {
124351
- this.embeddedRuntime = await this.spawnAedes(entry);
124352
- }
124353
- async shutdownEmbedded() {
124354
- if (!this.embeddedRuntime) return;
124355
- const runtime = this.embeddedRuntime;
124356
- this.embeddedRuntime = null;
124357
- await this.closeRuntime(runtime);
124358
- }
124359
124697
  /** Spawn a dedicated onboard `aedes` server for an onboard entry. */
124360
124698
  async spawnOnboard(entry) {
124361
124699
  const runtime = await this.spawnAedes(entry);
@@ -124395,7 +124733,7 @@ var MqttBrokerAddon = class extends BaseAddon {
124395
124733
  * entry disappeared, and respawn runtimes whose port changed.
124396
124734
  */
124397
124735
  async reconcileOnboardRuntimes() {
124398
- const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => b.enabled !== false);
124736
+ const desiredEntries = this.activeExternalBrokers.filter(hasOnboard).filter((b) => isInstanceEnabled(b));
124399
124737
  const desired = desiredEntries.map((b) => ({
124400
124738
  id: b.id,
124401
124739
  port: b.onboard.port
@@ -124492,8 +124830,9 @@ var MqttBrokerAddon = class extends BaseAddon {
124492
124830
  * (or whose username was removed entirely) get force-closed.
124493
124831
  */
124494
124832
  reconcileEmbeddedClients() {
124495
- const runtime = this.embeddedRuntime;
124496
- if (!runtime) return;
124833
+ for (const runtime of this.onboardRuntimes.values()) this.reconcileRuntimeClients(runtime);
124834
+ }
124835
+ reconcileRuntimeClients(runtime) {
124497
124836
  const prevSnapshot = runtime.credentialsSnapshot;
124498
124837
  const nextSnapshot = this.buildCredentialsSnapshot();
124499
124838
  const affectedUsers = [];
@@ -124532,30 +124871,10 @@ var MqttBrokerAddon = class extends BaseAddon {
124532
124871
  for (const c of this.activeEmbeddedClients) m.set(c.username, c.passwordHash);
124533
124872
  return m;
124534
124873
  }
124535
- /**
124536
- * Reassemble the internal {@link EmbeddedBrokerEntry} from the flat
124537
- * `embedded*` config keys the settings form writes. Returns `null`
124538
- * when the embedded broker is disabled — that's the signal
124539
- * `onConfigChanged` / `onInitialize` use to decide whether to spawn
124540
- * or shut down the `aedes` instance.
124541
- */
124542
- deriveEmbeddedEntry() {
124543
- if (!this.config.embeddedEnabled) return null;
124544
- const username = this.config.embeddedUsername;
124545
- const password = this.config.embeddedPassword;
124546
- return {
124547
- id: this.config.embeddedId || "embedded",
124548
- name: "Embedded broker",
124549
- port: this.config.embeddedPort,
124550
- allowAnonymous: this.config.embeddedAllowAnonymous,
124551
- ...username.length > 0 ? { username } : {},
124552
- ...password.length > 0 ? { password } : {}
124553
- };
124554
- }
124555
124874
  collectExternalProbeInputs() {
124556
124875
  const out = [];
124557
124876
  for (const b of this.activeExternalBrokers) {
124558
- if (b.onboard !== void 0 || b.enabled === false) continue;
124877
+ if (b.onboard !== void 0 || !isInstanceEnabled(b)) continue;
124559
124878
  let password;
124560
124879
  try {
124561
124880
  password = this.storedPassword(b.password);
@@ -124588,19 +124907,13 @@ var MqttBrokerAddon = class extends BaseAddon {
124588
124907
  * here (no migration code ships): the operator's one-off `mqtt` step does.
124589
124908
  */
124590
124909
  reportRetiredCiphertext() {
124591
- const paths = retiredCiphertextPaths({
124592
- brokers: this.activeExternalBrokers,
124593
- embeddedPassword: this.config.embeddedPassword
124594
- });
124910
+ const paths = retiredCiphertextPaths({ brokers: this.activeExternalBrokers });
124595
124911
  if (paths.length === 0) return;
124596
124912
  const unreadable = [];
124597
124913
  const values = [...this.activeExternalBrokers.map((b) => ({
124598
124914
  id: `brokers[${b.id}].password`,
124599
124915
  v: b.password
124600
- })), {
124601
- id: "embeddedPassword",
124602
- v: this.config.embeddedPassword
124603
- }];
124916
+ }))];
124604
124917
  for (const { id, v } of values) try {
124605
124918
  this.storedPassword(v);
124606
124919
  } catch (err) {
@@ -124624,13 +124937,79 @@ var MqttBrokerAddon = class extends BaseAddon {
124624
124937
  }
124625
124938
  });
124626
124939
  }
124627
- brokerForm() {
124940
+ /**
124941
+ * The broker form. The create form (`id` null) offers "run an onboard broker" (CamStack hosts an
124942
+ * `aedes` server on this hub: a port, anonymous access) or an external URL; an existing onboard
124943
+ * broker edits only its credentials, since its address is the one it was given.
124944
+ */
124945
+ brokerForm(id, onboard) {
124946
+ const credentials = [{
124947
+ type: "text",
124948
+ key: "username",
124949
+ label: "Username",
124950
+ labelKey: "mqtt-broker:fullSettings.brokers.username.label"
124951
+ }, {
124952
+ type: "password",
124953
+ key: "password",
124954
+ label: "Password",
124955
+ labelKey: "mqtt-broker:fullSettings.brokers.password.label",
124956
+ showToggle: true
124957
+ }];
124958
+ if (onboard) return this.schema({ sections: [{
124959
+ id: "broker",
124960
+ title: "Onboard broker",
124961
+ description: "A CamStack-hosted broker on this hub. Its port was chosen when it was created.",
124962
+ columns: 1,
124963
+ fields: credentials
124964
+ }] });
124965
+ const creating = id === null;
124966
+ const external = {
124967
+ field: "onboard",
124968
+ equals: false
124969
+ };
124628
124970
  return this.schema({ sections: [{
124629
124971
  id: "broker",
124630
- title: "External broker",
124631
- description: "A broker running outside CamStack (mosquitto, EMQX, HiveMQ, cloud bridges, …). The password is kept in the keychain.",
124972
+ title: creating ? "MQTT broker" : "External broker",
124973
+ description: creating ? "Run a broker on this hub, or connect to one running outside CamStack (mosquitto, EMQX, HiveMQ, cloud bridges, …). The password is kept in the keychain." : "A broker running outside CamStack (mosquitto, EMQX, HiveMQ, cloud bridges, …). The password is kept in the keychain.",
124632
124974
  columns: 1,
124633
124975
  fields: [
124976
+ ...creating ? [
124977
+ {
124978
+ type: "boolean",
124979
+ key: "onboard",
124980
+ label: "Run an onboard broker",
124981
+ labelKey: "mqtt-broker:fullSettings.brokers.onboard.label",
124982
+ description: "Spin up a CamStack-hosted aedes broker on this hub instead of connecting to an external one. Each onboard broker gets its own dedicated server + port.",
124983
+ descriptionKey: "mqtt-broker:fullSettings.brokers.onboard.description",
124984
+ default: false
124985
+ },
124986
+ {
124987
+ type: "number",
124988
+ key: "port",
124989
+ label: "Port",
124990
+ labelKey: "mqtt-broker:fullSettings.brokers.port.label",
124991
+ placeholder: "(auto)",
124992
+ description: "TCP port for the onboard broker. Leave blank to auto-allocate a free port.",
124993
+ descriptionKey: "mqtt-broker:fullSettings.brokers.port.description",
124994
+ showWhen: {
124995
+ field: "onboard",
124996
+ equals: true
124997
+ }
124998
+ },
124999
+ {
125000
+ type: "boolean",
125001
+ key: "allowAnonymous",
125002
+ label: "Allow anonymous",
125003
+ labelKey: "mqtt-broker:fullSettings.brokers.allowAnonymous.label",
125004
+ description: "Permit clients to connect without a username/password.",
125005
+ descriptionKey: "mqtt-broker:fullSettings.brokers.allowAnonymous.description",
125006
+ default: false,
125007
+ showWhen: {
125008
+ field: "onboard",
125009
+ equals: true
125010
+ }
125011
+ }
125012
+ ] : [],
124634
125013
  {
124635
125014
  type: "text",
124636
125015
  key: "url",
@@ -124638,26 +125017,15 @@ var MqttBrokerAddon = class extends BaseAddon {
124638
125017
  labelKey: "mqtt-broker:fullSettings.brokers.url.label",
124639
125018
  description: "mqtt://, mqtts://, ws://, wss://",
124640
125019
  descriptionKey: "mqtt-broker:fullSettings.brokers.url.description",
124641
- required: true
124642
- },
124643
- {
124644
- type: "text",
124645
- key: "username",
124646
- label: "Username",
124647
- labelKey: "mqtt-broker:fullSettings.brokers.username.label"
124648
- },
124649
- {
124650
- type: "password",
124651
- key: "password",
124652
- label: "Password",
124653
- labelKey: "mqtt-broker:fullSettings.brokers.password.label",
124654
- showToggle: true
125020
+ ...creating ? { showWhen: external } : { required: true }
124655
125021
  },
125022
+ ...credentials,
124656
125023
  {
124657
125024
  type: "text",
124658
125025
  key: "clientIdPrefix",
124659
125026
  label: "Client id prefix",
124660
- labelKey: "mqtt-broker:fullSettings.brokers.clientIdPrefix.label"
125027
+ labelKey: "mqtt-broker:fullSettings.brokers.clientIdPrefix.label",
125028
+ ...creating ? { showWhen: external } : {}
124661
125029
  }
124662
125030
  ]
124663
125031
  }] });
@@ -124668,6 +125036,41 @@ var MqttBrokerAddon = class extends BaseAddon {
124668
125036
  if (handle === void 0) throw new Error("records are not available");
124669
125037
  return {
124670
125038
  readRawBrokers: async () => (await this.ctx.settings?.readAddonStore())?.["brokers"],
125039
+ readLegacyEmbedded: async () => {
125040
+ const raw = await this.ctx.settings?.readAddonStore() ?? {};
125041
+ const secrets = this.ctx.secrets;
125042
+ const { value } = secrets === void 0 ? { value: raw } : await resolveSecretMarkers(raw, secrets, {
125043
+ unresolved: "keep-marker",
125044
+ ownedBy: secrets.owner
125045
+ });
125046
+ const text = (key) => {
125047
+ const v = value[key];
125048
+ return typeof v === "string" && v.length > 0 ? v : void 0;
125049
+ };
125050
+ const port = value["embeddedPort"];
125051
+ const username = text("embeddedUsername");
125052
+ const password = this.storedPassword(text("embeddedPassword"));
125053
+ const enabled = value["embeddedEnabled"] === true;
125054
+ if (!(enabled || text("embeddedId") !== void 0 || username !== void 0 || password !== void 0)) return null;
125055
+ return {
125056
+ enabled,
125057
+ id: text("embeddedId") ?? "embedded",
125058
+ port: typeof port === "number" && Number.isInteger(port) ? port : 1883,
125059
+ allowAnonymous: value["embeddedAllowAnonymous"] === true,
125060
+ ...username !== void 0 ? { username } : {},
125061
+ ...password !== void 0 ? { password } : {}
125062
+ };
125063
+ },
125064
+ readRawEmbeddedKeys: async () => {
125065
+ const raw = await this.ctx.settings?.readAddonStore() ?? {};
125066
+ return Object.fromEntries(LEGACY_EMBEDDED_KEYS.filter((key) => key in raw).map((key) => [key, raw[key]]));
125067
+ },
125068
+ putOnboardRecord: async (id, body) => {
125069
+ await handle.put({
125070
+ id,
125071
+ data: mqttBrokersEntryKind.schema.parse(body)
125072
+ }, { ifRev: 0 });
125073
+ },
124671
125074
  readRecords: async () => {
124672
125075
  const page = await handle.query({ limit: 1e3 });
124673
125076
  return new Map(page.records.map((r) => [r.id, { hasPassword: (r.data.password ?? "").length > 0 }]));
@@ -124684,184 +125087,105 @@ var MqttBrokerAddon = class extends BaseAddon {
124684
125087
  return ["mqtt-broker", "broker"];
124685
125088
  }
124686
125089
  /**
124687
- * The embedded broker, its credentials and the ACL. The external brokers are records, listed
125090
+ * The credentials and the ACL of the onboard brokers. The brokers are records, listed
124688
125091
  * on the Brokers page and edited as integration instances (`brokerForm`).
124689
125092
  */
124690
125093
  async clusterSettingsSchema(cap) {
124691
125094
  if (cap !== "mqtt-broker" && cap !== "broker") return null;
124692
- return this.schema({ sections: [
124693
- {
124694
- id: "mqtt-broker-embedded",
124695
- title: "Embedded broker",
124696
- titleKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.title",
124697
- description: "Optional CamStack-hosted aedes broker. Enable it to run a broker on this hub without standing up an external one — its connection details are exposed through the `mqtt-broker` cap like any external entry.",
124698
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.description",
124699
- columns: 2,
124700
- fields: [
124701
- this.field({
124702
- type: "boolean",
124703
- key: "embeddedEnabled",
124704
- label: "Run embedded broker",
124705
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedEnabled.label",
124706
- description: "Starts an aedes broker on this hub. Disabling it shuts the broker down and disconnects clients.",
124707
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedEnabled.description",
124708
- style: "switch",
124709
- default: false
124710
- }),
124711
- this.field({
124712
- type: "number",
124713
- key: "embeddedPort",
124714
- label: "Port",
124715
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedPort.label",
124716
- description: "TCP port the embedded broker listens on.",
124717
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedPort.description",
124718
- min: 1,
124719
- max: 65535,
124720
- default: DEFAULT_EMBEDDED_PORT,
124721
- showWhen: {
124722
- field: "embeddedEnabled",
124723
- equals: true
124724
- }
124725
- }),
124726
- this.field({
124727
- type: "boolean",
124728
- key: "embeddedAllowAnonymous",
124729
- label: "Allow anonymous",
124730
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedAllowAnonymous.label",
124731
- description: "Permit clients to connect without a username/password.",
124732
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedAllowAnonymous.description",
124733
- style: "switch",
124734
- default: false,
124735
- showWhen: {
124736
- field: "embeddedEnabled",
124737
- equals: true
124738
- }
124739
- }),
124740
- this.field({
124741
- type: "text",
124742
- key: "embeddedUsername",
124743
- label: "Shared username",
124744
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedUsername.label",
124745
- description: "Legacy single-user fallback — used only when no per-client credentials are configured below.",
124746
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedUsername.description",
124747
- default: "",
124748
- showWhen: {
124749
- field: "embeddedEnabled",
124750
- equals: true
124751
- }
124752
- }),
124753
- this.field({
124754
- type: "password",
124755
- key: "embeddedPassword",
124756
- label: "Shared password",
124757
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedPassword.label",
124758
- description: "Kept in the keychain. Paired with the shared username above.",
124759
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded.embeddedPassword.description",
124760
- showToggle: true,
124761
- default: "",
124762
- showWhen: {
124763
- field: "embeddedEnabled",
124764
- equals: true
124765
- }
124766
- })
124767
- ]
124768
- },
124769
- {
124770
- id: "mqtt-broker-embedded-clients",
124771
- title: "Embedded broker — credentials",
124772
- titleKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.title",
124773
- description: "Per-client username + bcrypt password hash for the embedded aedes broker. Generate the hash with `npx bcrypt-cli` (or any bcrypt tool, cost factor 10) and paste it here.",
124774
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.description",
124775
- columns: 1,
124776
- fields: [{
124777
- type: "editable-array",
124778
- key: "embeddedClients",
124779
- label: "Clients",
124780
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.label",
124781
- emptyMessage: "No clients configured — embedded broker is in shared-creds / anonymous mode.",
124782
- addLabel: "Add client",
124783
- rowTitleTemplate: "{username}",
124784
- defaultItem: {
124785
- username: "",
124786
- passwordHash: ""
124787
- },
124788
- itemFields: [{
125095
+ return this.schema({ sections: [{
125096
+ id: "mqtt-broker-embedded-clients",
125097
+ title: "Embedded broker — credentials",
125098
+ titleKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.title",
125099
+ description: "Per-client username + bcrypt password hash for the embedded aedes broker. Generate the hash with `npx bcrypt-cli` (or any bcrypt tool, cost factor 10) and paste it here.",
125100
+ descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.description",
125101
+ columns: 1,
125102
+ fields: [{
125103
+ type: "editable-array",
125104
+ key: "embeddedClients",
125105
+ label: "Clients",
125106
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.label",
125107
+ emptyMessage: "No clients configured — embedded broker is in shared-creds / anonymous mode.",
125108
+ addLabel: "Add client",
125109
+ rowTitleTemplate: "{username}",
125110
+ defaultItem: {
125111
+ username: "",
125112
+ passwordHash: ""
125113
+ },
125114
+ itemFields: [{
125115
+ type: "text",
125116
+ key: "username",
125117
+ label: "Username",
125118
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.username.label"
125119
+ }, {
125120
+ type: "text",
125121
+ key: "passwordHash",
125122
+ label: "bcrypt hash",
125123
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.passwordHash.label",
125124
+ description: "bcrypt hash of the password (cost factor 10).",
125125
+ descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.passwordHash.description"
125126
+ }]
125127
+ }]
125128
+ }, {
125129
+ id: "mqtt-broker-embedded-acl",
125130
+ title: "Embedded broker — topic ACL",
125131
+ titleKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.title",
125132
+ description: "Per-user pub/sub allow-list. With zero rules the broker is fully open to authenticated clients. With at least one rule, every user needs at least one rule that matches the topic.",
125133
+ descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.description",
125134
+ columns: 1,
125135
+ fields: [{
125136
+ type: "editable-array",
125137
+ key: "embeddedAcl",
125138
+ label: "Rules",
125139
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.label",
125140
+ emptyMessage: "No ACL rules — embedded broker is wide open to authenticated users.",
125141
+ addLabel: "Add rule",
125142
+ rowTitleTemplate: "{username} → {topicPattern} ({access})",
125143
+ defaultItem: {
125144
+ username: "",
125145
+ topicPattern: "#",
125146
+ access: "both"
125147
+ },
125148
+ itemFields: [
125149
+ {
124789
125150
  type: "text",
124790
125151
  key: "username",
124791
125152
  label: "Username",
124792
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.username.label"
124793
- }, {
125153
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.username.label"
125154
+ },
125155
+ {
124794
125156
  type: "text",
124795
- key: "passwordHash",
124796
- label: "bcrypt hash",
124797
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.passwordHash.label",
124798
- description: "bcrypt hash of the password (cost factor 10).",
124799
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-clients.embeddedClients.passwordHash.description"
124800
- }]
124801
- }]
124802
- },
124803
- {
124804
- id: "mqtt-broker-embedded-acl",
124805
- title: "Embedded broker — topic ACL",
124806
- titleKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.title",
124807
- description: "Per-user pub/sub allow-list. With zero rules the broker is fully open to authenticated clients. With at least one rule, every user needs at least one rule that matches the topic.",
124808
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.description",
124809
- columns: 1,
124810
- fields: [{
124811
- type: "editable-array",
124812
- key: "embeddedAcl",
124813
- label: "Rules",
124814
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.label",
124815
- emptyMessage: "No ACL rules — embedded broker is wide open to authenticated users.",
124816
- addLabel: "Add rule",
124817
- rowTitleTemplate: "{username} → {topicPattern} ({access})",
124818
- defaultItem: {
124819
- username: "",
124820
- topicPattern: "#",
124821
- access: "both"
125157
+ key: "topicPattern",
125158
+ label: "Topic pattern",
125159
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.topicPattern.label",
125160
+ description: "MQTT wildcards: `+` = single level, `#` = multi-level.",
125161
+ descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.topicPattern.description"
124822
125162
  },
124823
- itemFields: [
124824
- {
124825
- type: "text",
124826
- key: "username",
124827
- label: "Username",
124828
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.username.label"
124829
- },
124830
- {
124831
- type: "text",
124832
- key: "topicPattern",
124833
- label: "Topic pattern",
124834
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.topicPattern.label",
124835
- description: "MQTT wildcards: `+` = single level, `#` = multi-level.",
124836
- descriptionKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.topicPattern.description"
124837
- },
124838
- {
124839
- type: "select",
124840
- key: "access",
124841
- label: "Access",
124842
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.label",
124843
- options: [
124844
- {
124845
- value: "sub",
124846
- label: "Subscribe only",
124847
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_sub.label"
124848
- },
124849
- {
124850
- value: "pub",
124851
- label: "Publish only",
124852
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_pub.label"
124853
- },
124854
- {
124855
- value: "both",
124856
- label: "Subscribe + publish",
124857
- labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_both.label"
124858
- }
124859
- ]
124860
- }
124861
- ]
124862
- }]
124863
- }
124864
- ] });
125163
+ {
125164
+ type: "select",
125165
+ key: "access",
125166
+ label: "Access",
125167
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.label",
125168
+ options: [
125169
+ {
125170
+ value: "sub",
125171
+ label: "Subscribe only",
125172
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_sub.label"
125173
+ },
125174
+ {
125175
+ value: "pub",
125176
+ label: "Publish only",
125177
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_pub.label"
125178
+ },
125179
+ {
125180
+ value: "both",
125181
+ label: "Subscribe + publish",
125182
+ labelKey: "mqtt-broker:fullSettings.s_mqtt-broker-embedded-acl.embeddedAcl.access.o_both.label"
125183
+ }
125184
+ ]
125185
+ }
125186
+ ]
125187
+ }]
125188
+ }] });
124865
125189
  }
124866
125190
  };
124867
125191
  /**
@@ -124891,13 +125215,6 @@ function bcryptCompareSafe(plain, hash) {
124891
125215
  }
124892
125216
  }
124893
125217
  /**
124894
- * Decide whether a config update to the embedded broker requires a full
124895
- * restart (port change) or can be hot-reloaded (credential / ACL change).
124896
- */
124897
- function requiresEmbeddedRespawn(desired, running) {
124898
- return desired.id !== running.id || desired.port !== running.port || desired.allowAnonymous !== running.allowAnonymous || desired.username !== running.username || desired.password !== running.password;
124899
- }
124900
- /**
124901
125218
  * Read the `username` field off an aedes Client without leaking a cast.
124902
125219
  * aedes attaches the username at runtime but its `.d.ts` doesn't carry
124903
125220
  * it — we narrow with a small structural check.
@@ -124950,15 +125267,5 @@ async function findFreePort() {
124950
125267
  });
124951
125268
  });
124952
125269
  }
124953
- function mapMqttStatus(s) {
124954
- switch (s) {
124955
- case "connected": return "connected";
124956
- case "disconnected": return "disconnected";
124957
- case "auth-failed": return "auth-failed";
124958
- case "unreachable": return "unreachable";
124959
- case "tls-error": return "error";
124960
- default: return "error";
124961
- }
124962
- }
124963
125270
  //#endregion
124964
125271
  export { MQTT_EMBEDDED_BCRYPT_ROUNDS, MqttBrokerAddon, MqttBrokerAddon as default };