@camstack/addon-smtp-nodemailer 1.2.148 → 1.2.150

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6020,7 +6020,7 @@ var ZodIssueCode = {
6020
6020
  var ZodFirstPartyTypeKind;
6021
6021
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6022
6022
  //#endregion
6023
- //#region ../types/dist/sleep-DEZaLbiu.mjs
6023
+ //#region ../types/dist/sleep-CmjWurK5.mjs
6024
6024
  /**
6025
6025
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6026
6026
  * window to float samples (D455).
@@ -6704,137 +6704,93 @@ async function runAddonMigrations(host, migrations, logger, options = {}) {
6704
6704
  blockOwner
6705
6705
  };
6706
6706
  }
6707
- /**
6708
- * Build a {@link DurableState} over a single store key. Transport-agnostic:
6709
- * `read`/`write` are the addon-store or device-store accessors. The whole
6710
- * validated value round-trips on every read/write — the schema is the
6711
- * single source of truth for what is persisted, so no hand-listed field
6712
- * set can drop a key on save.
6713
- */
6714
- function createDurableState(deps) {
6715
- const get = async () => {
6716
- const raw = (await deps.read())[deps.key];
6717
- if (raw === void 0) return deps.fallback;
6718
- const parsed = deps.schema.safeParse(raw);
6719
- if (!parsed.success) {
6720
- deps.onParseError?.(deps.key, parsed.error);
6721
- return deps.fallback;
6722
- }
6723
- return parsed.data;
6724
- };
6725
- const set = async (next) => {
6726
- const validated = deps.schema.parse(next);
6727
- await deps.write({ [deps.key]: validated });
6728
- };
6729
- const update = async (fn) => {
6730
- await set(fn(await get()));
6731
- };
6707
+ /** The record calls the one-switch migration makes, over the migration API. */
6708
+ function switchRecordsOverMigrationApi(api) {
6709
+ return { kind: (definition) => {
6710
+ const handle = api.records.kind(definition);
6711
+ return {
6712
+ get: (id) => handle.get({ id }),
6713
+ put: (input, opts) => handle.put({
6714
+ ...input,
6715
+ ...opts?.ifRev === void 0 ? {} : { ifRev: opts.ifRev }
6716
+ }),
6717
+ patch: (id, partial) => handle.patch({
6718
+ id,
6719
+ partial
6720
+ })
6721
+ };
6722
+ } };
6723
+ }
6724
+ function integrationRowsApiOver(api) {
6732
6725
  return {
6733
- get,
6734
- set,
6735
- update
6726
+ list: async () => (await api.integrations.list({})).integrations,
6727
+ readLegacyIntegrationRows: (input) => api.legacyRows.read(input),
6728
+ clearLegacyIntegrationRows: (input) => api.legacyRows.clear(input)
6736
6729
  };
6737
6730
  }
6738
- /**
6739
- * Per-node scoping for the shared addon-settings blob.
6740
- *
6741
- * An addon's settings store is hub-central (the `addon-settings` cap is
6742
- * hub-routed — the hub instance answers for every node), so fields whose
6743
- * value is a NODE fact (decoder backend, engine pick, probed hardware
6744
- * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
6745
- * the single shared blob. The SCHEMA field key stays bare: the write path
6746
- * ({@link scopePatch}) maps the bare field onto the target node's scoped
6747
- * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
6748
- * back, so UI forms and `resolveConfig` only ever see the bare key.
6749
- *
6750
- * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
6751
- * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
6752
- * schema and routes reads/writes through these helpers.
6753
- *
6754
- * ## No bare-key fallback — deliberate
6755
- *
6756
- * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
6757
- * scoped key resolves to `undefined` so the field's schema `default` wins —
6758
- * NEVER `store[base]` and never another node's value. A bare legacy key in
6759
- * the store is invisible to every node, hub included, so one node's
6760
- * selection can never leak onto another. (This generalizes the
6761
- * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
6762
- * arbitrary set of per-node field keys.)
6763
- *
6764
- * Pure functions only — no I/O, no imports beyond the language. This is a
6765
- * LEAF module: import it via its deep path, never from the root barrel.
6766
- */
6767
- /**
6768
- * Normalize a raw kernel node id to the bare node id used for scoping.
6769
- * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
6770
- * processes; per-node settings are per-NODE, so strip the addon segment.
6771
- * `undefined` / `null` / empty falls back to `'hub'`.
6772
- */
6773
- function normalizeNodeId(raw) {
6774
- if (raw === void 0 || raw === null || raw === "") return "hub";
6775
- const slashIdx = raw.indexOf("/");
6776
- if (slashIdx < 0) return raw;
6777
- const bare = raw.slice(0, slashIdx);
6778
- return bare === "" ? "hub" : bare;
6779
- }
6780
- /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
6781
- function nodeScopedKey(base, nodeId) {
6782
- return `${base}@${normalizeNodeId(nodeId)}`;
6783
- }
6784
- /**
6785
- * Read a node's value for a per-node field from the raw shared store:
6786
- * the node-scoped key when present, otherwise `undefined`.
6787
- * Deliberately NO bare-key fallback (see module doc) — the caller lets the
6788
- * schema `default` win on `undefined`.
6789
- */
6790
- function readNodeValue(store, base, nodeId) {
6791
- return store[nodeScopedKey(base, nodeId)];
6792
- }
6793
- /**
6794
- * Re-map a UI/settings patch so every bare perNode field persists under the
6795
- * TARGET node's scoped key; all other keys pass through unchanged. Used on
6796
- * the write path so a save for one node never clobbers another node's value
6797
- * (and the bare key is never written). Returns a new object — the input
6798
- * patch is not mutated.
6799
- */
6800
- function scopePatch(patch, perNodeKeys, nodeId) {
6801
- const out = {};
6802
- for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
6803
- return out;
6804
- }
6805
- /**
6806
- * Project the raw shared store onto the bare schema keys for ONE node so a
6807
- * UI schema (whose field keys are bare) hydrates from that node's own
6808
- * values:
6809
- *
6810
- * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
6811
- * - Every bare perNode key is dropped from the pass-through (a stray bare
6812
- * legacy key must never hydrate any node — no bare fallback).
6813
- * - THIS node's effective value ({@link readNodeValue}) is then laid onto
6814
- * each bare perNode key; when the node has no scoped key the bare key is
6815
- * left ABSENT so the field's schema `default` wins.
6816
- *
6817
- * Returns a new object — the input store is not mutated.
6818
- */
6819
- function projectStore(store, perNodeKeys, nodeId) {
6820
- const out = {};
6821
- for (const [key, value] of Object.entries(store)) {
6822
- if (key.includes("@")) continue;
6823
- if (perNodeKeys.has(key)) continue;
6824
- out[key] = value;
6731
+ var PREFIX = "records/";
6732
+ /** The base of every records failure. `detail` is the human part of the message. */
6733
+ var RecordsError = class extends Error {
6734
+ code;
6735
+ detail;
6736
+ constructor(code, detail) {
6737
+ super(`${PREFIX}${code}: ${detail}`);
6738
+ this.name = "RecordsError";
6739
+ this.code = code;
6740
+ this.detail = detail;
6825
6741
  }
6826
- for (const base of perNodeKeys) {
6827
- const value = readNodeValue(store, base, nodeId);
6828
- if (value !== void 0) out[base] = value;
6742
+ };
6743
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
6744
+ var RevConflictError = class extends RecordsError {
6745
+ constructor(detail) {
6746
+ super("rev-conflict", detail);
6747
+ this.name = "RevConflictError";
6829
6748
  }
6830
- return out;
6749
+ };
6750
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
6751
+ var RecordSecretUnavailableError = class extends RecordsError {
6752
+ constructor(detail) {
6753
+ super("secret-unavailable", detail);
6754
+ this.name = "RecordSecretUnavailableError";
6755
+ }
6756
+ };
6757
+ var InvalidRecordError = class extends RecordsError {
6758
+ constructor(detail) {
6759
+ super("invalid-record", detail);
6760
+ this.name = "InvalidRecordError";
6761
+ }
6762
+ };
6763
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
6764
+ var DeclarationRefusedError = class extends RecordsError {
6765
+ constructor(detail) {
6766
+ super("declaration-refused", detail);
6767
+ this.name = "DeclarationRefusedError";
6768
+ }
6769
+ };
6770
+ function linkTargetOf(meta) {
6771
+ if (typeof meta !== "object" || meta === null) return void 0;
6772
+ const link = Reflect.get(meta, "link");
6773
+ const parsed = LinkTargetSchema.safeParse(link);
6774
+ return parsed.success ? parsed.data : void 0;
6775
+ }
6776
+ var LinkTargetSchema = object({
6777
+ cap: string().min(1),
6778
+ kind: string().min(1).optional()
6779
+ });
6780
+ /** The links a kind declares, read from the meta of its body fields. */
6781
+ function linksOfKind(kind) {
6782
+ const schema = kind.schema;
6783
+ if (!(schema instanceof ZodObject)) return [];
6784
+ const links = [];
6785
+ for (const [field, fieldSchema] of Object.entries(schema.shape)) {
6786
+ const to = linkTargetOf(globalRegistry.get(fieldSchema));
6787
+ if (to !== void 0) links.push({
6788
+ field,
6789
+ to
6790
+ });
6791
+ }
6792
+ return links;
6831
6793
  }
6832
- /** Every scope, in the order the guard and the docs list them. */
6833
- var SCOPED_SETTINGS_SCOPES = [
6834
- "cluster",
6835
- "device-defaults",
6836
- "node"
6837
- ];
6838
6794
  /**
6839
6795
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6840
6796
  *
@@ -6969,6 +6925,643 @@ function parseSecretRef(ref) {
6969
6925
  fieldPath
6970
6926
  };
6971
6927
  }
6928
+ /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
6929
+ /** The files a kind may live in. `history` is device-history's (D850), never records. */
6930
+ var RECORD_DATABASES = ["settings", "events"];
6931
+ /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
6932
+ var RECORD_CLASSES = [
6933
+ "config",
6934
+ "ledger",
6935
+ "audit",
6936
+ "mirror",
6937
+ "ephemeral"
6938
+ ];
6939
+ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
6940
+ var RECORD_MAX_DATA_BYTES = 1024 * 1024;
6941
+ var RECORD_BATCH_MAX = 1e3;
6942
+ var RECORD_QUERY_MAX = 1e3;
6943
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
6944
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
6945
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
6946
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
6947
+ /**
6948
+ * Secret fields of a record, addressed the way a Zod schema declares them
6949
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
6950
+ * (`auth.accessToken`, `headers[].value`).
6951
+ *
6952
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
6953
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
6954
+ * key releases exactly that key's secret.
6955
+ *
6956
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
6957
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
6958
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
6959
+ * leaf names its element: `headers[X-Api].value`.
6960
+ *
6961
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
6962
+ */
6963
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
6964
+ function parseSecretPath(path) {
6965
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
6966
+ return path.split(".").map((raw) => {
6967
+ const each = raw.endsWith("[]");
6968
+ const map = raw.endsWith("{}");
6969
+ const key = each || map ? raw.slice(0, -2) : raw;
6970
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
6971
+ return {
6972
+ key,
6973
+ each,
6974
+ map
6975
+ };
6976
+ });
6977
+ }
6978
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
6979
+ function secretArrayPrefixes(path) {
6980
+ const segments = parseSecretPath(path);
6981
+ const prefixes = [];
6982
+ const walked = [];
6983
+ for (const segment of segments) {
6984
+ walked.push(segment.key);
6985
+ if (segment.each) prefixes.push(walked.join("."));
6986
+ }
6987
+ return prefixes;
6988
+ }
6989
+ function isRecord$6(value) {
6990
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6991
+ }
6992
+ function elementId(element, idKey, declared, prefix) {
6993
+ const id = isRecord$6(element) ? element[idKey] : void 0;
6994
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
6995
+ return id;
6996
+ }
6997
+ /**
6998
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
6999
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
7000
+ * result is a new body, `data` is untouched.
7001
+ */
7002
+ var REMOVE_LEAF = Symbol("remove-leaf");
7003
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
7004
+ if (!isRecord$6(node)) return node;
7005
+ const segment = segments[index];
7006
+ if (segment === void 0) return node;
7007
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
7008
+ const child = node[segment.key];
7009
+ const keys = [...walkedKeys, segment.key];
7010
+ const last = index === segments.length - 1;
7011
+ if (segment.each) {
7012
+ if (!Array.isArray(child)) return node;
7013
+ const prefix = keys.join(".");
7014
+ const idKey = arrayKeys[prefix];
7015
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
7016
+ const mapped = child.map((element) => {
7017
+ const id = elementId(element, idKey, declared, prefix);
7018
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
7019
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
7020
+ });
7021
+ return {
7022
+ ...node,
7023
+ [segment.key]: mapped
7024
+ };
7025
+ }
7026
+ if (segment.map) {
7027
+ if (!isRecord$6(child)) return node;
7028
+ const kept = Object.entries(child).map(([mapKey, value]) => {
7029
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
7030
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
7031
+ return [mapKey, visit({
7032
+ declared,
7033
+ concrete,
7034
+ value
7035
+ })];
7036
+ }).filter(([, value]) => value !== REMOVE_LEAF);
7037
+ return {
7038
+ ...node,
7039
+ [segment.key]: Object.fromEntries(kept)
7040
+ };
7041
+ }
7042
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
7043
+ if (last) {
7044
+ const replacement = visit({
7045
+ declared,
7046
+ concrete,
7047
+ value: child
7048
+ });
7049
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
7050
+ return {
7051
+ ...node,
7052
+ [segment.key]: replacement
7053
+ };
7054
+ }
7055
+ return {
7056
+ ...node,
7057
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
7058
+ };
7059
+ }
7060
+ /** Replace/remove every present secret leaf; returns a NEW body. */
7061
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
7062
+ let current = data;
7063
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
7064
+ return current;
7065
+ }
7066
+ /**
7067
+ * The keychain collection name a kind's secrets live under. Prefixed so a
7068
+ * record's refs never collide with the refs a legacy collection of the same name
7069
+ * already holds during an adoption.
7070
+ */
7071
+ function recordSecretCollection(kind) {
7072
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
7073
+ }
7074
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
7075
+ function recordSecretRef(owner, kind, rowId, concretePath) {
7076
+ return buildSecretRef({
7077
+ owner,
7078
+ scope: {
7079
+ kind: "row",
7080
+ collection: recordSecretCollection(kind),
7081
+ rowId
7082
+ },
7083
+ fieldPath: concretePath
7084
+ });
7085
+ }
7086
+ /**
7087
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
7088
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
7089
+ * token. The form hands it to the secret field, which reveals the value by ref
7090
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
7091
+ * stored secret (the records door reads a view as KEEP).
7092
+ *
7093
+ * ONE implementation for the entries service and for every addon that serves
7094
+ * its own instances (`RecordIntegrationInstances`).
7095
+ */
7096
+ function isRecord$5(value) {
7097
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7098
+ }
7099
+ function secretViewsOf(owner, kind, id, decl, data) {
7100
+ if (decl.secretPaths.length === 0) return data;
7101
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
7102
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
7103
+ return {
7104
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
7105
+ v: 1,
7106
+ set: true
7107
+ };
7108
+ });
7109
+ return isRecord$5(shown) ? shown : data;
7110
+ }
7111
+ /** The most instances one addon lists (an integrations page, not a table). */
7112
+ var INSTANCES_LIST_MAX = 1e3;
7113
+ /**
7114
+ * The ONE reader of an instance's switch (D996): an absent field means on, so a row written
7115
+ * before the field existed needs no migration. Every consumer of an instance body asks this.
7116
+ */
7117
+ function isInstanceEnabled(body) {
7118
+ return body.enabled !== false;
7119
+ }
7120
+ /** The body key of the switch; only {@link RecordIntegrationInstances.setInstanceEnabled} writes it. */
7121
+ var SWITCH_KEY = "enabled";
7122
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
7123
+ function topLevelSecretKeys(paths) {
7124
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
7125
+ }
7126
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
7127
+ function secretMapKeys(paths) {
7128
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
7129
+ }
7130
+ /**
7131
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
7132
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
7133
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
7134
+ */
7135
+ function secretMapPatch(value) {
7136
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
7137
+ const out = {};
7138
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
7139
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
7140
+ return Object.keys(out).length > 0 ? out : null;
7141
+ }
7142
+ var RecordIntegrationInstances = class {
7143
+ records;
7144
+ kind;
7145
+ hooks;
7146
+ handle;
7147
+ secretKeys;
7148
+ secretMaps;
7149
+ nameField;
7150
+ switchListeners = /* @__PURE__ */ new Set();
7151
+ constructor(records, kind, hooks) {
7152
+ this.records = records;
7153
+ this.kind = kind;
7154
+ this.hooks = hooks;
7155
+ this.handle = records.kind(kind);
7156
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
7157
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
7158
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
7159
+ }
7160
+ /**
7161
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
7162
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
7163
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
7164
+ */
7165
+ async readResolved(id) {
7166
+ try {
7167
+ const record = await this.handle.getResolved(id);
7168
+ return record === null ? null : {
7169
+ id,
7170
+ body: record.data,
7171
+ enabled: isInstanceEnabled(record.data),
7172
+ secrets: "resolved"
7173
+ };
7174
+ } catch (err) {
7175
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
7176
+ const stored = await this.handle.get(id);
7177
+ if (stored === null) return null;
7178
+ return {
7179
+ id,
7180
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
7181
+ enabled: isInstanceEnabled(stored.data),
7182
+ secrets: "unavailable"
7183
+ };
7184
+ }
7185
+ }
7186
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
7187
+ async getResolved(id) {
7188
+ return (await this.readResolved(id))?.body ?? null;
7189
+ }
7190
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
7191
+ async listResolved() {
7192
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
7193
+ const out = [];
7194
+ for (const record of page.records) {
7195
+ const read = await this.readResolved(record.id);
7196
+ if (read !== null) out.push(read);
7197
+ }
7198
+ return out;
7199
+ }
7200
+ viewOf(record) {
7201
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
7202
+ const rawName = record.data[this.nameField];
7203
+ const kind = this.hooks.kindOf?.(record.data);
7204
+ const health = this.hooks.health?.(record.data, record.id);
7205
+ return {
7206
+ id: record.id,
7207
+ name: typeof rawName === "string" ? rawName : record.id,
7208
+ configured: this.hooks.configured(record.data),
7209
+ enabled: isInstanceEnabled(record.data),
7210
+ formValues: shown,
7211
+ ...kind !== void 0 ? { kind } : {},
7212
+ ...health?.status !== void 0 ? { status: health.status } : {},
7213
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
7214
+ };
7215
+ }
7216
+ describe = async () => {
7217
+ const declared = linksOfKind(this.kind);
7218
+ const links = this.hooks.description.links !== void 0 || declared.length === 0 ? {} : { links: declared.map((link) => ({
7219
+ kind: this.kind.name,
7220
+ field: link.field,
7221
+ to: link.to
7222
+ })) };
7223
+ return {
7224
+ ...this.hooks.description,
7225
+ ...links,
7226
+ ...this.hooks.mintId === void 0 ? {} : { mintsId: true }
7227
+ };
7228
+ };
7229
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
7230
+ listInstances = async () => {
7231
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
7232
+ };
7233
+ getInstance = async ({ id }) => {
7234
+ const record = await this.handle.get(id);
7235
+ return record === null ? null : this.viewOf(record);
7236
+ };
7237
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
7238
+ createInstance = async ({ id, name, kind, values }) => {
7239
+ const minted = id ?? this.hooks.mintId?.({
7240
+ name,
7241
+ ...kind !== void 0 ? { kind } : {}
7242
+ });
7243
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
7244
+ await this.handle.put({
7245
+ id: minted,
7246
+ data: this.hooks.initialBody(name, kind)
7247
+ }, { ifRev: 0 });
7248
+ const patch = this.patchOf(values ?? {});
7249
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
7250
+ await this.hooks.onChanged?.(minted, "created");
7251
+ return { id: minted };
7252
+ };
7253
+ updateInstance = async ({ id, name, values }) => {
7254
+ const patch = this.patchOf(values);
7255
+ if (name !== void 0) patch[this.nameField] = name;
7256
+ await this.handle.patch(id, patch);
7257
+ await this.hooks.onChanged?.(id, "updated");
7258
+ return { ok: true };
7259
+ };
7260
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
7261
+ patchOf(values) {
7262
+ const patch = {};
7263
+ for (const [key, value] of Object.entries(values)) {
7264
+ if (value === void 0) continue;
7265
+ if (key === "enabled") continue;
7266
+ if (this.secretMaps.has(key)) {
7267
+ const entries = secretMapPatch(value);
7268
+ if (entries !== null) patch[key] = entries;
7269
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
7270
+ else if (isSecretClear(value)) patch[key] = null;
7271
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
7272
+ }
7273
+ return patch;
7274
+ }
7275
+ /**
7276
+ * Listen to the switch of ANY instance of this helper (in the process that serves it). The
7277
+ * durable replacement of the `integration.enabled` / `integration.disabled` events (D8): the
7278
+ * addon reconciles from the record, whichever way it flipped.
7279
+ */
7280
+ onSwitched(listener) {
7281
+ this.switchListeners.add(listener);
7282
+ }
7283
+ /**
7284
+ * The ONE writer of the switch (D996, D1014): the record body's `enabled`, for every role. A
7285
+ * configured thing is an instance, so an id with no record yet (a default integration that was
7286
+ * never configured) gets its record from `initialBody` before the switch is written.
7287
+ */
7288
+ setInstanceEnabled = async ({ id, enabled }) => {
7289
+ if (await this.handle.get(id) === null) await this.handle.put({
7290
+ id,
7291
+ data: this.hooks.initialBody(id)
7292
+ }, { ifRev: 0 });
7293
+ await this.handle.patch(id, { [SWITCH_KEY]: enabled });
7294
+ await this.hooks.onChanged?.(id, "enabled");
7295
+ for (const listener of this.switchListeners) await listener(id, enabled);
7296
+ return { ok: true };
7297
+ };
7298
+ /** The row and its keychain refs go together (the records door). */
7299
+ deleteInstance = async ({ id }) => {
7300
+ await this.handle.delete(id);
7301
+ await this.hooks.onChanged?.(id, "deleted");
7302
+ return { ok: true };
7303
+ };
7304
+ testInstance = async (input) => {
7305
+ if (this.hooks.test === void 0) return {
7306
+ success: false,
7307
+ status: "unsupported",
7308
+ error: "This integration declares no connection test"
7309
+ };
7310
+ return this.hooks.test(input);
7311
+ };
7312
+ /** The flat provider object to hand to `registerProvider`. */
7313
+ toProvider() {
7314
+ return {
7315
+ describe: this.describe,
7316
+ instanceFormSchema: this.instanceFormSchema,
7317
+ listInstances: this.listInstances,
7318
+ getInstance: this.getInstance,
7319
+ createInstance: this.createInstance,
7320
+ updateInstance: this.updateInstance,
7321
+ setInstanceEnabled: this.setInstanceEnabled,
7322
+ deleteInstance: this.deleteInstance,
7323
+ testInstance: this.testInstance
7324
+ };
7325
+ }
7326
+ };
7327
+ /**
7328
+ * The one-switch migration (epic #440, step 3). An integration's on/off state used to live in the
7329
+ * registry's `enabled` column for a device addon; it now lives only in the instance record's
7330
+ * body (`enabled`, D1007 superseded). This moves a registry `enabled = false` into the body, once.
7331
+ *
7332
+ * For every registry row of the addon that is OFF:
7333
+ * - no record under its id: the record is created from `initialBody(name)` with `enabled: false`
7334
+ * (a default integration that never had settings, Reolink's among them);
7335
+ * - a record whose body states no `enabled`: `enabled: false` is written into it;
7336
+ * - a record that already states `enabled` (either way) is the newer truth and is left alone.
7337
+ * A row that is ON writes nothing: an absent field reads as on. A rerun finds every off row with
7338
+ * a stated switch and does nothing, so nothing switched off comes back on and nothing switched on
7339
+ * goes off. The registry column itself is neither read afterwards nor written; its drop is step 5.
7340
+ *
7341
+ * It runs in the addon process, BEFORE the addon registers its `integration-instances` provider,
7342
+ * which is also why `integrations.list` still answers the stored column at that point.
7343
+ */
7344
+ function registrySwitchToBodyId(addonId, date) {
7345
+ return `${addonId}/${date}-registry-switch-to-body`;
7346
+ }
7347
+ async function moveRegistrySwitchToBody(ports, spec) {
7348
+ const rows = await ports.listIntegrations(spec.addonId);
7349
+ let created = 0;
7350
+ let switched = 0;
7351
+ let kept = 0;
7352
+ for (const row of rows) {
7353
+ if (row.enabled) continue;
7354
+ const body = await ports.readBody(row.id);
7355
+ if (body === null) {
7356
+ if (await ports.createRecord(row.id, {
7357
+ ...spec.initialBody(row.name),
7358
+ ["enabled"]: false
7359
+ }) === "created") created += 1;
7360
+ else kept += 1;
7361
+ continue;
7362
+ }
7363
+ if ("enabled" in body) {
7364
+ kept += 1;
7365
+ continue;
7366
+ }
7367
+ await ports.switchOff(row.id);
7368
+ switched += 1;
7369
+ }
7370
+ const summary = {
7371
+ integrations: rows.length,
7372
+ off: rows.filter((r) => !r.enabled).length,
7373
+ created,
7374
+ switched,
7375
+ kept
7376
+ };
7377
+ return created === 0 && switched === 0 ? {
7378
+ outcome: "already-done",
7379
+ summary
7380
+ } : {
7381
+ outcome: "done",
7382
+ summary
7383
+ };
7384
+ }
7385
+ /** A migration entry: an addon states its kind and how a new body starts, nothing else. */
7386
+ function registrySwitchToBodyMigration(spec) {
7387
+ return {
7388
+ meta: {
7389
+ id: registrySwitchToBodyId(spec.addonId, spec.date),
7390
+ owner: spec.addonId,
7391
+ level: "addon-state",
7392
+ seq: spec.seq,
7393
+ dependsOn: [],
7394
+ store: "settings",
7395
+ scope: "cluster",
7396
+ onFailure: "block-owner",
7397
+ bodyKind: "procedure",
7398
+ description: "Move the registry enabled flag of every switched-off integration into its instance record body, creating the record when there is none",
7399
+ fixtureMark: "enabled"
7400
+ },
7401
+ procedure: (ports) => moveRegistrySwitchToBody(ports, {
7402
+ addonId: spec.addonId,
7403
+ initialBody: spec.initialBody
7404
+ })
7405
+ };
7406
+ }
7407
+ /** The hub and records sides of {@link registrySwitchToBodyMigration}. */
7408
+ function registrySwitchPortsOver(deps) {
7409
+ const handle = deps.records.kind({
7410
+ name: deps.kind.name,
7411
+ declaration: deps.kind.declaration,
7412
+ schema: record(string(), unknown())
7413
+ });
7414
+ return {
7415
+ listIntegrations: async (addonId) => (await deps.api.list()).filter((i) => i.addonId === addonId).map((i) => ({
7416
+ id: i.id,
7417
+ name: i.name,
7418
+ enabled: i.enabled !== false
7419
+ })),
7420
+ readBody: async (id) => (await handle.get(id))?.data ?? null,
7421
+ createRecord: async (id, body) => {
7422
+ if (await handle.get(id) !== null) return "exists";
7423
+ await handle.put({
7424
+ id,
7425
+ data: body
7426
+ }, { ifRev: 0 });
7427
+ return "created";
7428
+ },
7429
+ switchOff: async (id) => {
7430
+ await handle.patch(id, { [SWITCH_KEY]: false });
7431
+ }
7432
+ };
7433
+ }
7434
+ /**
7435
+ * Build a {@link DurableState} over a single store key. Transport-agnostic:
7436
+ * `read`/`write` are the addon-store or device-store accessors. The whole
7437
+ * validated value round-trips on every read/write — the schema is the
7438
+ * single source of truth for what is persisted, so no hand-listed field
7439
+ * set can drop a key on save.
7440
+ */
7441
+ function createDurableState(deps) {
7442
+ const get = async () => {
7443
+ const raw = (await deps.read())[deps.key];
7444
+ if (raw === void 0) return deps.fallback;
7445
+ const parsed = deps.schema.safeParse(raw);
7446
+ if (!parsed.success) {
7447
+ deps.onParseError?.(deps.key, parsed.error);
7448
+ return deps.fallback;
7449
+ }
7450
+ return parsed.data;
7451
+ };
7452
+ const set = async (next) => {
7453
+ const validated = deps.schema.parse(next);
7454
+ await deps.write({ [deps.key]: validated });
7455
+ };
7456
+ const update = async (fn) => {
7457
+ await set(fn(await get()));
7458
+ };
7459
+ return {
7460
+ get,
7461
+ set,
7462
+ update
7463
+ };
7464
+ }
7465
+ /**
7466
+ * Per-node scoping for the shared addon-settings blob.
7467
+ *
7468
+ * An addon's settings store is hub-central (the `addon-settings` cap is
7469
+ * hub-routed — the hub instance answers for every node), so fields whose
7470
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
7471
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
7472
+ * the single shared blob. The SCHEMA field key stays bare: the write path
7473
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
7474
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
7475
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
7476
+ *
7477
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
7478
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
7479
+ * schema and routes reads/writes through these helpers.
7480
+ *
7481
+ * ## No bare-key fallback — deliberate
7482
+ *
7483
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
7484
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
7485
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
7486
+ * the store is invisible to every node, hub included, so one node's
7487
+ * selection can never leak onto another. (This generalizes the
7488
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
7489
+ * arbitrary set of per-node field keys.)
7490
+ *
7491
+ * Pure functions only — no I/O, no imports beyond the language. This is a
7492
+ * LEAF module: import it via its deep path, never from the root barrel.
7493
+ */
7494
+ /**
7495
+ * Normalize a raw kernel node id to the bare node id used for scoping.
7496
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
7497
+ * processes; per-node settings are per-NODE, so strip the addon segment.
7498
+ * `undefined` / `null` / empty falls back to `'hub'`.
7499
+ */
7500
+ function normalizeNodeId(raw) {
7501
+ if (raw === void 0 || raw === null || raw === "") return "hub";
7502
+ const slashIdx = raw.indexOf("/");
7503
+ if (slashIdx < 0) return raw;
7504
+ const bare = raw.slice(0, slashIdx);
7505
+ return bare === "" ? "hub" : bare;
7506
+ }
7507
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
7508
+ function nodeScopedKey(base, nodeId) {
7509
+ return `${base}@${normalizeNodeId(nodeId)}`;
7510
+ }
7511
+ /**
7512
+ * Read a node's value for a per-node field from the raw shared store:
7513
+ * the node-scoped key when present, otherwise `undefined`.
7514
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
7515
+ * schema `default` win on `undefined`.
7516
+ */
7517
+ function readNodeValue(store, base, nodeId) {
7518
+ return store[nodeScopedKey(base, nodeId)];
7519
+ }
7520
+ /**
7521
+ * Re-map a UI/settings patch so every bare perNode field persists under the
7522
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
7523
+ * the write path so a save for one node never clobbers another node's value
7524
+ * (and the bare key is never written). Returns a new object — the input
7525
+ * patch is not mutated.
7526
+ */
7527
+ function scopePatch(patch, perNodeKeys, nodeId) {
7528
+ const out = {};
7529
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
7530
+ return out;
7531
+ }
7532
+ /**
7533
+ * Project the raw shared store onto the bare schema keys for ONE node so a
7534
+ * UI schema (whose field keys are bare) hydrates from that node's own
7535
+ * values:
7536
+ *
7537
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
7538
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
7539
+ * legacy key must never hydrate any node — no bare fallback).
7540
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
7541
+ * each bare perNode key; when the node has no scoped key the bare key is
7542
+ * left ABSENT so the field's schema `default` wins.
7543
+ *
7544
+ * Returns a new object — the input store is not mutated.
7545
+ */
7546
+ function projectStore(store, perNodeKeys, nodeId) {
7547
+ const out = {};
7548
+ for (const [key, value] of Object.entries(store)) {
7549
+ if (key.includes("@")) continue;
7550
+ if (perNodeKeys.has(key)) continue;
7551
+ out[key] = value;
7552
+ }
7553
+ for (const base of perNodeKeys) {
7554
+ const value = readNodeValue(store, base, nodeId);
7555
+ if (value !== void 0) out[base] = value;
7556
+ }
7557
+ return out;
7558
+ }
7559
+ /** Every scope, in the order the guard and the docs list them. */
7560
+ var SCOPED_SETTINGS_SCOPES = [
7561
+ "cluster",
7562
+ "device-defaults",
7563
+ "node"
7564
+ ];
6972
7565
  /** A write to a secret path could not be stored in the keychain, so it was refused. */
6973
7566
  var KeychainWriteRefusedError = class extends Error {
6974
7567
  fieldPath;
@@ -6979,7 +7572,7 @@ var KeychainWriteRefusedError = class extends Error {
6979
7572
  }
6980
7573
  };
6981
7574
  var KEEP = { kind: "keep" };
6982
- function isRecord$6(value) {
7575
+ function isRecord$4(value) {
6983
7576
  return typeof value === "object" && value !== null && !Array.isArray(value);
6984
7577
  }
6985
7578
  function defaultMintId() {
@@ -6992,7 +7585,7 @@ function collectSecretMarkerRefs(value, out = []) {
6992
7585
  return out;
6993
7586
  }
6994
7587
  if (Array.isArray(value)) for (const item of value) collectSecretMarkerRefs(item, out);
6995
- else if (isRecord$6(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
7588
+ else if (isRecord$4(value)) for (const child of Object.values(value)) collectSecretMarkerRefs(child, out);
6996
7589
  return out;
6997
7590
  }
6998
7591
  async function storedValueEquals(secrets, marker, candidate) {
@@ -7047,7 +7640,7 @@ function rowId(row, idKey) {
7047
7640
  return null;
7048
7641
  }
7049
7642
  async function writeArray(ctx, node, incoming, stored, fieldPath) {
7050
- const storedRows = Array.isArray(stored) ? stored.filter(isRecord$6) : [];
7643
+ const storedRows = Array.isArray(stored) ? stored.filter(isRecord$4) : [];
7051
7644
  if (!Array.isArray(incoming)) {
7052
7645
  ctx.deletes.push(...collectSecretMarkerRefs(storedRows));
7053
7646
  return {
@@ -7063,7 +7656,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
7063
7656
  const kept = /* @__PURE__ */ new Set();
7064
7657
  const rows = [];
7065
7658
  for (const row of incoming) {
7066
- if (!isRecord$6(row)) {
7659
+ if (!isRecord$4(row)) {
7067
7660
  rows.push(row);
7068
7661
  continue;
7069
7662
  }
@@ -7088,7 +7681,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7088
7681
  case "leaf": return writeLeaf(ctx, incoming, stored, fieldPath);
7089
7682
  case "array": return writeArray(ctx, node, incoming, stored, fieldPath);
7090
7683
  case "object": {
7091
- if (!isRecord$6(incoming)) {
7684
+ if (!isRecord$4(incoming)) {
7092
7685
  if (incoming === void 0) return KEEP;
7093
7686
  ctx.deletes.push(...collectSecretMarkerRefs(stored));
7094
7687
  return {
@@ -7096,7 +7689,7 @@ async function writeNode(ctx, node, incoming, stored, fieldPath) {
7096
7689
  value: incoming
7097
7690
  };
7098
7691
  }
7099
- const storedObj = isRecord$6(stored) ? stored : {};
7692
+ const storedObj = isRecord$4(stored) ? stored : {};
7100
7693
  return {
7101
7694
  kind: "value",
7102
7695
  value: await writeMembers(ctx, node.children, incoming, storedObj, (m) => `${fieldPath}.${m}`)
@@ -7219,7 +7812,7 @@ async function resolveSecretMarkers(value, secrets, options = {}) {
7219
7812
  value: items
7220
7813
  };
7221
7814
  }
7222
- if (isRecord$6(v)) {
7815
+ if (isRecord$4(v)) {
7223
7816
  const out = {};
7224
7817
  for (const [k, child] of Object.entries(v)) {
7225
7818
  const s = substitute(child);
@@ -7251,7 +7844,7 @@ var SecretOverwriteRefusedError = class extends Error {
7251
7844
  this.name = "SecretOverwriteRefusedError";
7252
7845
  }
7253
7846
  };
7254
- function isRecord$5(value) {
7847
+ function isRecord$3(value) {
7255
7848
  return typeof value === "object" && value !== null && !Array.isArray(value);
7256
7849
  }
7257
7850
  function resolvedValue(pass, marker) {
@@ -7280,7 +7873,7 @@ function inArray(pass, incoming, stored) {
7280
7873
  return incoming.map((item, index) => {
7281
7874
  const twin = stored[index];
7282
7875
  if (isSecretMarker(twin)) return typeof item === "string" && item === resolvedValue(pass, twin) ? twin : item;
7283
- if (isRecord$5(item) && isRecord$5(twin)) return inArrayRow(pass, item, twin);
7876
+ if (isRecord$3(item) && isRecord$3(twin)) return inArrayRow(pass, item, twin);
7284
7877
  if (Array.isArray(item) && Array.isArray(twin)) return inArray(pass, item, twin);
7285
7878
  return item;
7286
7879
  });
@@ -7291,7 +7884,7 @@ function inArrayRow(pass, incoming, stored) {
7291
7884
  const twin = stored[key];
7292
7885
  if (isSecretMarker(twin)) {
7293
7886
  if (typeof value === "string" && value === resolvedValue(pass, twin)) out[key] = twin;
7294
- } else if (isRecord$5(value) && isRecord$5(twin)) out[key] = inArrayRow(pass, value, twin);
7887
+ } else if (isRecord$3(value) && isRecord$3(twin)) out[key] = inArrayRow(pass, value, twin);
7295
7888
  else if (Array.isArray(value) && Array.isArray(twin)) out[key] = inArray(pass, value, twin);
7296
7889
  }
7297
7890
  return out;
@@ -7299,7 +7892,7 @@ function inArrayRow(pass, incoming, stored) {
7299
7892
  async function walk(pass, incoming, stored) {
7300
7893
  if (isSecretMarker(stored)) return atMarker(pass, incoming, stored);
7301
7894
  if (Array.isArray(incoming) && Array.isArray(stored)) return inArray(pass, incoming, stored);
7302
- if (!isRecord$5(incoming) || !isRecord$5(stored)) return incoming;
7895
+ if (!isRecord$3(incoming) || !isRecord$3(stored)) return incoming;
7303
7896
  const out = { ...incoming };
7304
7897
  for (const [key, value] of Object.entries(incoming)) out[key] = await walk(pass, value, stored[key]);
7305
7898
  return out;
@@ -7330,7 +7923,7 @@ async function restoreUnchangedSecrets(input) {
7330
7923
  function isJsonEqual(a, b) {
7331
7924
  if (Object.is(a, b)) return true;
7332
7925
  if (Array.isArray(a)) return Array.isArray(b) && a.length === b.length && a.every((v, i) => isJsonEqual(v, b[i]));
7333
- if (isRecord$5(a) && isRecord$5(b)) {
7926
+ if (isRecord$3(a) && isRecord$3(b)) {
7334
7927
  const keys = Object.keys(a);
7335
7928
  if (keys.length !== Object.keys(b).length) return false;
7336
7929
  return keys.every((k) => Object.prototype.hasOwnProperty.call(b, k) && isJsonEqual(a[k], b[k]));
@@ -7354,7 +7947,7 @@ function markerKeysOf(blob, owner) {
7354
7947
  }
7355
7948
  function nodeFromStored(value, owner) {
7356
7949
  if (isSecretMarker(value)) return isSecretRefOwnedBy(value.$secret, owner) ? { kind: "leaf" } : null;
7357
- if (!isRecord$5(value)) return null;
7950
+ if (!isRecord$3(value)) return null;
7358
7951
  const children = /* @__PURE__ */ new Map();
7359
7952
  for (const [key, child] of Object.entries(value)) {
7360
7953
  const node = nodeFromStored(child, owner);
@@ -7649,6 +8242,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7649
8242
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7650
8243
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7651
8244
  /**
8245
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
8246
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
8247
+ * through `api` (guard `check-migration-ports-surface`).
8248
+ */
8249
+ function migrationSet(catalogue, bindPorts) {
8250
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
8251
+ }
8252
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
8253
+ function refuseMixed(form, kept, dropped) {
8254
+ 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`);
8255
+ }
8256
+ function catalogueOf(list) {
8257
+ const kept = list.filter((entry) => !("execute" in entry));
8258
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
8259
+ return kept;
8260
+ }
8261
+ function boundOf(list) {
8262
+ const kept = list.filter((entry) => "execute" in entry);
8263
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
8264
+ return kept;
8265
+ }
8266
+ /**
7652
8267
  * Base class for CamStack addons. Eliminates settings boilerplate:
7653
8268
  *
7654
8269
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7815,29 +8430,62 @@ var BaseAddon = class {
7815
8430
  await this.loadScopedSchemas();
7816
8431
  return normalized;
7817
8432
  }
8433
+ async runMigrations(first, second, third) {
8434
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
8435
+ return this.runBound(boundOf(first), second);
8436
+ }
7818
8437
  /**
7819
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7820
- * engine. Call it at the point of the boot where the data must already have the new
7821
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7822
- * restored devices — with the catalogue bound to the addon's ports
7823
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7824
- *
7825
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7826
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7827
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7828
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7829
- *
7830
- * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7831
- * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7832
- * omitted applied ids "newer").
8438
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
8439
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
8440
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
8441
+ */
8442
+ async runMigrationSets(sets, options) {
8443
+ const api = this.ctx.migrationApi;
8444
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
8445
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
8446
+ }
8447
+ /**
8448
+ * A device addon states its instance kind once, before its migrations run, and the one-switch
8449
+ * migration (registry `enabled` to the instance body, epic #440 step 3) joins whatever
8450
+ * catalogue the addon runs, in the SAME declaration (the engine replaces an owner's catalogue
8451
+ * on every declare).
7833
8452
  */
7834
- async runMigrations(migrations, options) {
8453
+ declareRegistrySwitch(spec) {
8454
+ this.registrySwitchSpec = spec;
8455
+ }
8456
+ registrySwitchSpec = null;
8457
+ registrySwitchBound() {
8458
+ const spec = this.registrySwitchSpec;
8459
+ if (spec === null) return [];
8460
+ const api = this.ctx.migrationApi;
8461
+ if (api === void 0) {
8462
+ this.ctx.logger.warn("the registry switch migration is skipped: the migration API is not available on this context");
8463
+ return [];
8464
+ }
8465
+ return migrationSet([registrySwitchToBodyMigration({
8466
+ addonId: this.ctx.id,
8467
+ date: "2026-11-06",
8468
+ seq: 1e3,
8469
+ initialBody: spec.initialBody
8470
+ })], (a) => registrySwitchPortsOver({
8471
+ api: integrationRowsApiOver(a),
8472
+ records: switchRecordsOverMigrationApi(a),
8473
+ kind: spec.kind
8474
+ })).bind(api);
8475
+ }
8476
+ async runBound(declared, options) {
8477
+ const added = this.registrySwitchBound();
8478
+ const migrations = [...declared, ...added];
8479
+ const phased = options?.only === void 0 || added.length === 0 ? options : {
8480
+ ...options,
8481
+ only: [...options.only, ...added.map((m) => m.meta.id)]
8482
+ };
7835
8483
  const api = this.ctx.api.migrations;
7836
8484
  const report = await runAddonMigrations({
7837
8485
  declareOwner: (input) => api.declareOwner.mutate(input),
7838
8486
  startMigration: (input) => api.startMigration.mutate(input),
7839
8487
  finishMigration: (input) => api.finishMigration.mutate(input)
7840
- }, migrations, this.ctx.logger, options);
8488
+ }, migrations, this.ctx.logger, phased);
7841
8489
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7842
8490
  return report;
7843
8491
  }
@@ -8910,228 +9558,6 @@ function normalizeAddonInitResult(result) {
8910
9558
  if (Array.isArray(result)) return { providers: result };
8911
9559
  return result;
8912
9560
  }
8913
- var PREFIX = "records/";
8914
- /** The base of every records failure. `detail` is the human part of the message. */
8915
- var RecordsError = class extends Error {
8916
- code;
8917
- detail;
8918
- constructor(code, detail) {
8919
- super(`${PREFIX}${code}: ${detail}`);
8920
- this.name = "RecordsError";
8921
- this.code = code;
8922
- this.detail = detail;
8923
- }
8924
- };
8925
- /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8926
- var RevConflictError = class extends RecordsError {
8927
- constructor(detail) {
8928
- super("rev-conflict", detail);
8929
- this.name = "RevConflictError";
8930
- }
8931
- };
8932
- /** The keychain could not store or serve a value: explicit, never an empty string. */
8933
- var RecordSecretUnavailableError = class extends RecordsError {
8934
- constructor(detail) {
8935
- super("secret-unavailable", detail);
8936
- this.name = "RecordSecretUnavailableError";
8937
- }
8938
- };
8939
- var InvalidRecordError = class extends RecordsError {
8940
- constructor(detail) {
8941
- super("invalid-record", detail);
8942
- this.name = "InvalidRecordError";
8943
- }
8944
- };
8945
- /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8946
- var DeclarationRefusedError = class extends RecordsError {
8947
- constructor(detail) {
8948
- super("declaration-refused", detail);
8949
- this.name = "DeclarationRefusedError";
8950
- }
8951
- };
8952
- /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8953
- /** The files a kind may live in. `history` is device-history's (D850), never records. */
8954
- var RECORD_DATABASES = ["settings", "events"];
8955
- /** The classes of a kind: the `@durable` vocabulary, one authority (replaces the annotation). */
8956
- var RECORD_CLASSES = [
8957
- "config",
8958
- "ledger",
8959
- "audit",
8960
- "mirror",
8961
- "ephemeral"
8962
- ];
8963
- var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8964
- var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8965
- var RECORD_BATCH_MAX = 1e3;
8966
- var RECORD_QUERY_MAX = 1e3;
8967
- /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8968
- var RECORD_SETTINGS_MAX_ROWS = 5e4;
8969
- /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8970
- var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8971
- /**
8972
- * Secret fields of a record, addressed the way a Zod schema declares them
8973
- * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8974
- * (`auth.accessToken`, `headers[].value`).
8975
- *
8976
- * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8977
- * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8978
- * key releases exactly that key's secret.
8979
- *
8980
- * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8981
- * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8982
- * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8983
- * leaf names its element: `headers[X-Api].value`.
8984
- *
8985
- * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8986
- */
8987
- /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8988
- function parseSecretPath(path) {
8989
- if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8990
- return path.split(".").map((raw) => {
8991
- const each = raw.endsWith("[]");
8992
- const map = raw.endsWith("{}");
8993
- const key = each || map ? raw.slice(0, -2) : raw;
8994
- if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8995
- return {
8996
- key,
8997
- each,
8998
- map
8999
- };
9000
- });
9001
- }
9002
- /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
9003
- function secretArrayPrefixes(path) {
9004
- const segments = parseSecretPath(path);
9005
- const prefixes = [];
9006
- const walked = [];
9007
- for (const segment of segments) {
9008
- walked.push(segment.key);
9009
- if (segment.each) prefixes.push(walked.join("."));
9010
- }
9011
- return prefixes;
9012
- }
9013
- function isRecord$4(value) {
9014
- return typeof value === "object" && value !== null && !Array.isArray(value);
9015
- }
9016
- function elementId(element, idKey, declared, prefix) {
9017
- const id = isRecord$4(element) ? element[idKey] : void 0;
9018
- 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`);
9019
- return id;
9020
- }
9021
- /**
9022
- * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
9023
- * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
9024
- * result is a new body, `data` is untouched.
9025
- */
9026
- var REMOVE_LEAF = Symbol("remove-leaf");
9027
- function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
9028
- if (!isRecord$4(node)) return node;
9029
- const segment = segments[index];
9030
- if (segment === void 0) return node;
9031
- if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
9032
- const child = node[segment.key];
9033
- const keys = [...walkedKeys, segment.key];
9034
- const last = index === segments.length - 1;
9035
- if (segment.each) {
9036
- if (!Array.isArray(child)) return node;
9037
- const prefix = keys.join(".");
9038
- const idKey = arrayKeys[prefix];
9039
- if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
9040
- const mapped = child.map((element) => {
9041
- const id = elementId(element, idKey, declared, prefix);
9042
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
9043
- return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
9044
- });
9045
- return {
9046
- ...node,
9047
- [segment.key]: mapped
9048
- };
9049
- }
9050
- if (segment.map) {
9051
- if (!isRecord$4(child)) return node;
9052
- const kept = Object.entries(child).map(([mapKey, value]) => {
9053
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
9054
- if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
9055
- return [mapKey, visit({
9056
- declared,
9057
- concrete,
9058
- value
9059
- })];
9060
- }).filter(([, value]) => value !== REMOVE_LEAF);
9061
- return {
9062
- ...node,
9063
- [segment.key]: Object.fromEntries(kept)
9064
- };
9065
- }
9066
- const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
9067
- if (last) {
9068
- const replacement = visit({
9069
- declared,
9070
- concrete,
9071
- value: child
9072
- });
9073
- if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9074
- return {
9075
- ...node,
9076
- [segment.key]: replacement
9077
- };
9078
- }
9079
- return {
9080
- ...node,
9081
- [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9082
- };
9083
- }
9084
- /** Replace/remove every present secret leaf; returns a NEW body. */
9085
- function mapSecretLeaves(data, paths, arrayKeys, visit) {
9086
- let current = data;
9087
- for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9088
- return current;
9089
- }
9090
- /**
9091
- * The keychain collection name a kind's secrets live under. Prefixed so a
9092
- * record's refs never collide with the refs a legacy collection of the same name
9093
- * already holds during an adoption.
9094
- */
9095
- function recordSecretCollection(kind) {
9096
- return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9097
- }
9098
- /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9099
- function recordSecretRef(owner, kind, rowId, concretePath) {
9100
- return buildSecretRef({
9101
- owner,
9102
- scope: {
9103
- kind: "row",
9104
- collection: recordSecretCollection(kind),
9105
- rowId
9106
- },
9107
- fieldPath: concretePath
9108
- });
9109
- }
9110
- /**
9111
- * A stored secret, as an admin read shows it: a VIEW naming the row's own
9112
- * keychain ref (`set: true`), never the value and no longer the bare redaction
9113
- * token. The form hands it to the secret field, which reveals the value by ref
9114
- * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9115
- * stored secret (the records door reads a view as KEEP).
9116
- *
9117
- * ONE implementation for the entries service and for every addon that serves
9118
- * its own instances (`RecordIntegrationInstances`).
9119
- */
9120
- function isRecord$3(value) {
9121
- return typeof value === "object" && value !== null && !Array.isArray(value);
9122
- }
9123
- function secretViewsOf(owner, kind, id, decl, data) {
9124
- if (decl.secretPaths.length === 0) return data;
9125
- const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9126
- if (leaf.value !== "__camstack_redacted__") return leaf.value;
9127
- return {
9128
- $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9129
- v: 1,
9130
- set: true
9131
- };
9132
- });
9133
- return isRecord$3(shown) ? shown : data;
9134
- }
9135
9561
  /**
9136
9562
  * The share-view scope kinds a share-link token can carry. The hub mints
9137
9563
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9385,6 +9811,7 @@ function defineRecordKinds(specs) {
9385
9811
  function entryBody(shape) {
9386
9812
  return object({
9387
9813
  name: string().min(1),
9814
+ enabled: boolean().optional(),
9388
9815
  ...shape
9389
9816
  });
9390
9817
  }
@@ -11224,6 +11651,10 @@ Object.freeze({
11224
11651
  "all",
11225
11652
  "one"
11226
11653
  ]
11654
+ },
11655
+ {
11656
+ "path": "positionUpdatedAt",
11657
+ "valueType": "number"
11227
11658
  }
11228
11659
  ],
11229
11660
  "meter": [{
@@ -11478,22 +11909,6 @@ Object.freeze({
11478
11909
  "path": "pumpRunning",
11479
11910
  "valueType": "boolean"
11480
11911
  },
11481
- {
11482
- "path": "lastDrink",
11483
- "valueType": "number"
11484
- },
11485
- {
11486
- "path": "currentHourDrink",
11487
- "valueType": "number"
11488
- },
11489
- {
11490
- "path": "last24hDrink",
11491
- "valueType": "number"
11492
- },
11493
- {
11494
- "path": "todayDrink",
11495
- "valueType": "number"
11496
- },
11497
11912
  {
11498
11913
  "path": "error",
11499
11914
  "valueType": "string"
@@ -12059,6 +12474,60 @@ Object.freeze({
12059
12474
  }
12060
12475
  ]
12061
12476
  });
12477
+ Object.freeze({
12478
+ "actions": { "run": 363e4 },
12479
+ "audio-analyzer": { "classify": 3e4 },
12480
+ "custom-model-registry": { "importModelBundle": 18e5 },
12481
+ "database-snapshot": { "writeSnapshot": 18e5 },
12482
+ "device-manager": {
12483
+ "migrateDevice": 72e4,
12484
+ "runDiscoverySweep": 12e4
12485
+ },
12486
+ "device-provider": { "reloadDevice": 18e4 },
12487
+ "llm": {
12488
+ "generate": 6e5,
12489
+ "generateVision": 6e5,
12490
+ "testProfile": 6e5
12491
+ },
12492
+ "llm-runtime": {
12493
+ "complete": 6e5,
12494
+ "completeApple": 6e5,
12495
+ "ensureStarted": 6e5,
12496
+ "installModel": 36e5
12497
+ },
12498
+ "local-network": { "scanNetwork": 9e4 },
12499
+ "model-convert": { "convert": 6e5 },
12500
+ "pipeline-analytics": {
12501
+ "addRetrainFrameFromRecording": 6e4,
12502
+ "offerRetrainArchive": 12e4,
12503
+ "proposeRetrainAnnotationsWithLlm": 18e4,
12504
+ "resolveRetrainTrainingCorpus": 6e4,
12505
+ "writeRetrainArchive": 36e5
12506
+ },
12507
+ "server-management": { "applyServerUpdate": 96e4 },
12508
+ "terminal-session": { "pullOutput": 15e3 },
12509
+ "training": {
12510
+ "canaryResult": 12e4,
12511
+ "cancelJob": 12e4,
12512
+ "planJob": 6e4,
12513
+ "registerResult": 18e5,
12514
+ "rollbackCanary": 12e4,
12515
+ "startJob": 12e4,
12516
+ "startJobBatch": 12e4
12517
+ },
12518
+ "training-provider": {
12519
+ "cancelJob": 6e4,
12520
+ "cleanupJob": 3e5,
12521
+ "getJob": 6e4,
12522
+ "listJobEvents": 6e4,
12523
+ "listJobs": 12e4,
12524
+ "offerArtifact": 3e5,
12525
+ "readResult": 3e5,
12526
+ "submitJob": 18e5,
12527
+ "uploadDataset": 72e5,
12528
+ "validateCredentials": 3e4
12529
+ }
12530
+ });
12062
12531
  object({
12063
12532
  code: string().regex(/^[a-z][a-z0-9-]*(\.[a-z0-9-]+)+$/),
12064
12533
  params: record(string(), union([string(), number()])).optional()
@@ -12078,7 +12547,7 @@ function userError(code, params, englishFallback) {
12078
12547
  return new CamstackError(code, params, englishFallback);
12079
12548
  }
12080
12549
  //#endregion
12081
- //#region ../types/dist/composition-pOHbTzRB.mjs
12550
+ //#region ../types/dist/composition-BmBHuDTQ.mjs
12082
12551
  /**
12083
12552
  * The ffmpeg build every CamStack node downloads, per platform and arch.
12084
12553
  *
@@ -12382,7 +12851,7 @@ var table = {
12382
12851
  },
12383
12852
  dwell: {
12384
12853
  minArgs: 3,
12385
- maxArgs: 3,
12854
+ maxArgs: 4,
12386
12855
  apply: () => {
12387
12856
  throw new ExpressionEvalError("dwell: stateful evaluation context is required");
12388
12857
  }
@@ -13442,219 +13911,80 @@ var IntegrationInstanceRefSchema = object({
13442
13911
  ]),
13443
13912
  candidateStableId: string().optional()
13444
13913
  });
13445
- /**
13446
- * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13447
- * entry kind, so an addon that holds a connection serves it in ~30 lines.
13448
- *
13449
- * Every instance is one record of the addon's own kind, keyed by the
13450
- * `integrations` registry id. The records door does the secret work: a field the
13451
- * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13452
- * deleting the row deletes the secret, and one row's value is never another's.
13453
- *
13454
- * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13455
- * token or the view the form was given KEEP the stored secret;
13456
- * `{ $secretClear: true }` clears it; any other string replaces it.
13457
- */
13458
- /** The most instances one addon lists (an integrations page, not a table). */
13459
- var INSTANCES_LIST_MAX = 1e3;
13460
- /** The keys of the kind's secret fields that sit at the top level of the body. */
13461
- function topLevelSecretKeys(paths) {
13462
- return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13463
- }
13464
- /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13465
- function secretMapKeys(paths) {
13466
- return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13467
- }
13468
- /**
13469
- * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13470
- * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13471
- * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13472
- */
13473
- function secretMapPatch(value) {
13474
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13475
- const out = {};
13476
- for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13477
- else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13478
- return Object.keys(out).length > 0 ? out : null;
13479
- }
13480
- /** Does the kind's body schema carry an `enabled` field? */
13481
- function declaresEnabled(kind) {
13482
- const json = toJSONSchema(kind.schema, {
13483
- unrepresentable: "any",
13484
- io: "input"
13485
- });
13486
- const properties = Reflect.get(json, "properties");
13487
- return typeof properties === "object" && properties !== null && "enabled" in properties;
13488
- }
13489
- var RecordIntegrationInstances = class {
13490
- records;
13491
- kind;
13492
- hooks;
13493
- handle;
13494
- secretKeys;
13495
- secretMaps;
13496
- nameField;
13497
- /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13498
- registryOwnsEnabled;
13499
- constructor(records, kind, hooks) {
13500
- this.records = records;
13501
- this.kind = kind;
13502
- this.hooks = hooks;
13503
- this.handle = records.kind(kind);
13504
- this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13505
- this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13506
- this.nameField = kind.declaration.entry?.nameField ?? "name";
13507
- this.registryOwnsEnabled = hooks.description.role === "devices";
13508
- 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"`);
13509
- }
13510
- /**
13511
- * One instance read for the addon's own runtime; null when absent. When the keychain is
13512
- * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13513
- * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13514
- */
13515
- async readResolved(id) {
13516
- try {
13517
- const record = await this.handle.getResolved(id);
13518
- return record === null ? null : {
13519
- id,
13520
- body: record.data,
13521
- enabled: record.data.enabled !== false,
13522
- secrets: "resolved"
13523
- };
13524
- } catch (err) {
13525
- if (!(err instanceof RecordSecretUnavailableError)) throw err;
13526
- const stored = await this.handle.get(id);
13527
- if (stored === null) return null;
13528
- return {
13529
- id,
13530
- body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13531
- enabled: stored.data.enabled !== false,
13532
- secrets: "unavailable"
13533
- };
13534
- }
13535
- }
13536
- /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13537
- async getResolved(id) {
13538
- return (await this.readResolved(id))?.body ?? null;
13539
- }
13540
- /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13541
- async listResolved() {
13542
- const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13543
- const out = [];
13544
- for (const record of page.records) {
13545
- const read = await this.readResolved(record.id);
13546
- if (read !== null) out.push(read);
13547
- }
13548
- return out;
13549
- }
13550
- viewOf(record) {
13551
- const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13552
- const rawName = record.data[this.nameField];
13553
- const kind = this.hooks.kindOf?.(record.data);
13554
- const health = this.hooks.health?.(record.data, record.id);
13555
- return {
13556
- id: record.id,
13557
- name: typeof rawName === "string" ? rawName : record.id,
13558
- configured: this.hooks.configured(record.data),
13559
- ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13560
- formValues: shown,
13561
- ...kind !== void 0 ? { kind } : {},
13562
- ...health?.status !== void 0 ? { status: health.status } : {},
13563
- ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13564
- };
13914
+ /** No part holds the id a call named. */
13915
+ var UnknownInstanceError = class extends Error {
13916
+ instanceId;
13917
+ constructor(instanceId) {
13918
+ super(`Unknown instance '${instanceId}'`);
13919
+ this.instanceId = instanceId;
13920
+ this.name = "UnknownInstanceError";
13565
13921
  }
13566
- describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13567
- ...this.hooks.description,
13568
- mintsId: true
13569
- };
13570
- /**
13571
- * The record an id names. A caller holding the `integrations` registry id (the Integrations
13572
- * page) reaches a kind whose body links to it through `integrationId`; an id that is itself a
13573
- * record id answers as it is. An id that names nothing comes back unchanged.
13574
- */
13575
- async resolveRecordId(id) {
13576
- if (await this.handle.get(id) !== null) return id;
13577
- const linked = (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.find((record) => record.data["integrationId"] === id);
13578
- return linked === void 0 ? id : linked.id;
13922
+ };
13923
+ /** A create or a form named no kind, or a kind no part serves. */
13924
+ var UnknownInstanceKindError = class extends Error {
13925
+ kindId;
13926
+ constructor(kindId) {
13927
+ super(kindId === void 0 ? "This provider has several kinds: name one" : `Unknown instance kind '${kindId}'`);
13928
+ this.kindId = kindId;
13929
+ this.name = "UnknownInstanceKindError";
13579
13930
  }
13580
- instanceFormSchema = async ({ id }) => this.hooks.formSchema(id === null ? null : await this.resolveRecordId(id));
13581
- listInstances = async () => {
13582
- return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13931
+ };
13932
+ function composeInstanceKinds(parts, base) {
13933
+ const byKind = (kindId) => {
13934
+ if (kindId === void 0) {
13935
+ const only = parts.length === 1 ? parts[0] : void 0;
13936
+ if (only === void 0) throw new UnknownInstanceKindError(void 0);
13937
+ return only;
13938
+ }
13939
+ const part = parts.find((candidate) => candidate.kind.id === kindId);
13940
+ if (part === void 0) throw new UnknownInstanceKindError(kindId);
13941
+ return part;
13583
13942
  };
13584
- getInstance = async ({ id }) => {
13585
- const record = await this.handle.get(await this.resolveRecordId(id));
13586
- return record === null ? null : this.viewOf(record);
13943
+ const holderOf = async (id) => {
13944
+ for (const part of parts) if (await part.provider.getInstance({ id }) !== null) return part;
13945
+ throw new UnknownInstanceError(id);
13587
13946
  };
13588
- /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13589
- createInstance = async ({ id, name, kind }) => {
13590
- const minted = id ?? this.hooks.mintId?.({
13591
- name,
13592
- ...kind !== void 0 ? { kind } : {}
13593
- });
13594
- if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13595
- await this.handle.put({
13596
- id: minted,
13597
- data: this.hooks.initialBody(name, kind)
13598
- }, { ifRev: 0 });
13599
- await this.hooks.onChanged?.(minted, "created");
13600
- return { id: minted };
13601
- };
13602
- updateInstance = async ({ id: askedId, name, values }) => {
13603
- const id = await this.resolveRecordId(askedId);
13604
- const patch = {};
13605
- for (const [key, value] of Object.entries(values)) {
13606
- if (value === void 0) continue;
13607
- if (this.secretMaps.has(key)) {
13608
- const entries = secretMapPatch(value);
13609
- if (entries !== null) patch[key] = entries;
13610
- } else if (!this.secretKeys.has(key)) patch[key] = value;
13611
- else if (isSecretClear(value)) patch[key] = null;
13612
- else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13947
+ const tagged = (part, instance) => ({
13948
+ ...instance,
13949
+ kind: part.kind.id
13950
+ });
13951
+ return {
13952
+ describe: async () => {
13953
+ const links = (await Promise.all(parts.map(async (part) => (await part.provider.describe()).links ?? []))).flat();
13954
+ return {
13955
+ ...base,
13956
+ kinds: parts.map((part) => part.kind),
13957
+ ...links.length > 0 ? { links } : {}
13958
+ };
13959
+ },
13960
+ instanceFormSchema: async ({ id, kind }) => {
13961
+ return (id === null ? byKind(kind) : await holderOf(id)).provider.instanceFormSchema({ id });
13962
+ },
13963
+ listInstances: async () => {
13964
+ return (await Promise.all(parts.map(async (part) => (await part.provider.listInstances()).map((instance) => tagged(part, instance))))).flat();
13965
+ },
13966
+ getInstance: async ({ id }) => {
13967
+ for (const part of parts) {
13968
+ const found = await part.provider.getInstance({ id });
13969
+ if (found !== null) return tagged(part, found);
13970
+ }
13971
+ return null;
13972
+ },
13973
+ createInstance: async (input) => byKind(input.kind).provider.createInstance(input),
13974
+ updateInstance: async (input) => (await holderOf(input.id)).provider.updateInstance(input),
13975
+ setInstanceEnabled: async (input) => (await holderOf(input.id)).provider.setInstanceEnabled(input),
13976
+ deleteInstance: async (input) => (await holderOf(input.id)).provider.deleteInstance(input),
13977
+ testInstance: async (input) => {
13978
+ const test = (input.id === null ? byKind(input.kind) : await holderOf(input.id)).provider.testInstance;
13979
+ if (test === void 0) return {
13980
+ success: false,
13981
+ status: "inconclusive",
13982
+ error: "This kind cannot be tested"
13983
+ };
13984
+ return test(input);
13613
13985
  }
13614
- if (name !== void 0) patch[this.nameField] = name;
13615
- await this.handle.patch(id, patch);
13616
- await this.hooks.onChanged?.(id, "updated");
13617
- return { ok: true };
13618
- };
13619
- /** The switch lives in the record body; the addon is told so it applies it (D996). */
13620
- setInstanceEnabled = async ({ id, enabled }) => {
13621
- if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13622
- await this.handle.patch(id, { enabled });
13623
- await this.hooks.onChanged?.(id, "enabled");
13624
- return { ok: true };
13625
- };
13626
- /** The row and its keychain refs go together (the records door). */
13627
- deleteInstance = async ({ id }) => {
13628
- await this.handle.delete(id);
13629
- await this.hooks.onChanged?.(id, "deleted");
13630
- return { ok: true };
13631
- };
13632
- testInstance = async (input) => {
13633
- if (this.hooks.test === void 0) return {
13634
- success: false,
13635
- status: "unsupported",
13636
- error: "This integration declares no connection test"
13637
- };
13638
- return this.hooks.test(input.id === null ? input : {
13639
- ...input,
13640
- id: await this.resolveRecordId(input.id)
13641
- });
13642
13986
  };
13643
- /** The flat provider object to hand to `registerProvider`. */
13644
- toProvider() {
13645
- return {
13646
- describe: this.describe,
13647
- instanceFormSchema: this.instanceFormSchema,
13648
- listInstances: this.listInstances,
13649
- getInstance: this.getInstance,
13650
- createInstance: this.createInstance,
13651
- updateInstance: this.updateInstance,
13652
- setInstanceEnabled: this.setInstanceEnabled,
13653
- deleteInstance: this.deleteInstance,
13654
- testInstance: this.testInstance
13655
- };
13656
- }
13657
- };
13987
+ }
13658
13988
  var EncodeProfileSchema = object({
13659
13989
  video: object({
13660
13990
  codec: _enum([
@@ -15827,6 +16157,39 @@ var UnstampedEventMediaCountSchema = object({
15827
16157
  /** Sum across both, or `null` when either lane could not be counted. */
15828
16158
  total: number().int().nonnegative().nullable()
15829
16159
  }).nullable();
16160
+ /**
16161
+ * Where the stored event media sits, per storage location: how many media rows
16162
+ * and how many bytes carry each location id, how many carry none (legacy,
16163
+ * resolved to the default `eventMedia` location), and how many name a location
16164
+ * that was not asked about (a deleted or never-listed one).
16165
+ *
16166
+ * One covering-index aggregate per asked location plus the NULL one, and one
16167
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
16168
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
16169
+ * it is a deleted location only when every location id was asked.
16170
+ * `null` is "could not be measured", never zero.
16171
+ */
16172
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
16173
+ var MediaLocationCensusSchema = object({
16174
+ locations: array(object({
16175
+ locationId: string(),
16176
+ rows: number().int().nonnegative(),
16177
+ bytes: number().nonnegative()
16178
+ })).readonly(),
16179
+ unstamped: object({
16180
+ rows: number().int().nonnegative(),
16181
+ bytes: number().nonnegative()
16182
+ }),
16183
+ /** Rows stamped with a location id that was not in the asked list. */
16184
+ unlisted: object({
16185
+ rows: number().int().nonnegative(),
16186
+ bytes: number().nonnegative()
16187
+ }),
16188
+ total: object({
16189
+ rows: number().int().nonnegative(),
16190
+ bytes: number().nonnegative()
16191
+ })
16192
+ });
15830
16193
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15831
16194
  /** The independently selectable logical storage classes — every class
15832
16195
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -19806,31 +20169,21 @@ var APPLIANCE_CAP_VOCABULARY = {
19806
20169
  "pet-fountain": {
19807
20170
  scope: "device",
19808
20171
  noun: t("Pet fountain", "Fontana per animali"),
19809
- actions: [
19810
- {
19811
- id: "petFountain.pumpOn",
19812
- method: "setPump",
19813
- label: t("Pump on", "Pompa accesa"),
19814
- phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
19815
- icon: "play",
19816
- args: { on: true }
19817
- },
19818
- {
19819
- id: "petFountain.pumpOff",
19820
- method: "setPump",
19821
- label: t("Pump off", "Pompa spenta"),
19822
- phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
19823
- icon: "square",
19824
- args: { on: false }
19825
- },
19826
- {
19827
- id: "petFountain.resetDailyConsumption",
19828
- method: "resetDailyConsumption",
19829
- label: t("Clear daily consumption", "Azzera il consumo giornaliero"),
19830
- phrase: t("Clear the daily water consumption of {device}", "Azzera il consumo giornaliero di acqua di {device}"),
19831
- icon: "rotate-ccw"
19832
- }
19833
- ],
20172
+ actions: [{
20173
+ id: "petFountain.pumpOn",
20174
+ method: "setPump",
20175
+ label: t("Pump on", "Pompa accesa"),
20176
+ phrase: t("Start the pump of {device}", "Avvia la pompa di {device}"),
20177
+ icon: "play",
20178
+ args: { on: true }
20179
+ }, {
20180
+ id: "petFountain.pumpOff",
20181
+ method: "setPump",
20182
+ label: t("Pump off", "Pompa spenta"),
20183
+ phrase: t("Stop the pump of {device}", "Ferma la pompa di {device}"),
20184
+ icon: "square",
20185
+ args: { on: false }
20186
+ }],
19834
20187
  state: [{
19835
20188
  kind: "boolean",
19836
20189
  field: "empty",
@@ -43724,8 +44077,15 @@ var ActionInputSchema = object({
43724
44077
  var ActionRunOriginSchema = object({
43725
44078
  /** The automation block whose step started it. */
43726
44079
  blockId: string().min(1).optional() });
43727
- /** `started` = the caller did not ask to wait. */
43728
- var ActionRunOutcomeSchema = union([AutomationRunOutcomeSchema, literal("started")]);
44080
+ /**
44081
+ * `started` = the caller did not ask to wait. `timed-out` = the run reached the
44082
+ * ceiling (`ACTION_RUN_MAX_MS`) and was stopped; it is never a `ran`.
44083
+ */
44084
+ var ActionRunOutcomeSchema = union([
44085
+ AutomationRunOutcomeSchema,
44086
+ literal("started"),
44087
+ literal("timed-out")
44088
+ ]);
43729
44089
  var ActionRunResultSchema = object({
43730
44090
  runId: string().min(1),
43731
44091
  outcome: ActionRunOutcomeSchema,
@@ -44247,6 +44607,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44247
44607
  kind: "mutation",
44248
44608
  auth: "admin"
44249
44609
  });
44610
+ /** `timeoutMs` of `actions.run`: a waited call outlives any legal run. */
44611
+ var ACTION_RUN_TIMEOUT_MS = 363e4;
44250
44612
  /**
44251
44613
  * actions — the ONE surface for runnable actions, for the UI and for
44252
44614
  * automations. Provided by the core-blocks builtin on the hub.
@@ -44265,6 +44627,12 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44265
44627
  * An admin, and an in-process caller (an automation block), may run any action.
44266
44628
  * Every refusal is typed (`[not-linked] …`) and logged.
44267
44629
  *
44630
+ * **A run lasts at most `ACTION_RUN_MAX_MS` (60 min).** The provider stops a
44631
+ * run that reaches it and answers `timed-out` (never `ran`); an action whose
44632
+ * `wait` steps alone add up to more is refused at create/update
44633
+ * (`[invalid-steps]`). `run` declares a `timeoutMs` above that ceiling, so a
44634
+ * waited call (an automation step) is never cut by the 60 s transport default.
44635
+ *
44268
44636
  * A second `run` of an action that is already running is REFUSED — traced and
44269
44637
  * logged — never queued.
44270
44638
  */
@@ -44291,7 +44659,8 @@ method(object({}), array(ActionEntrySchema), { auth: "admin" }), method(object({
44291
44659
  role: "viewer",
44292
44660
  auth: "protected",
44293
44661
  kind: "mutation",
44294
- caller: "required"
44662
+ caller: "required",
44663
+ timeoutMs: ACTION_RUN_TIMEOUT_MS
44295
44664
  }), method(ActionIdInput, _void(), {
44296
44665
  kind: "mutation",
44297
44666
  auth: "admin"
@@ -46347,52 +46716,7 @@ DeviceType.Light, method(object({
46347
46716
  level: number().min(0).max(100),
46348
46717
  lastChangedAt: number()
46349
46718
  });
46350
- /**
46351
- * `broker` — unified pub/sub broker registry, system-scoped collection.
46352
- *
46353
- * The cap models any kind-tagged message broker the user wants to
46354
- * register and that other addons might consume. The first two kinds
46355
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
46356
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
46357
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
46358
- * the same surface.
46359
- *
46360
- * Why one cap, not one cap per kind:
46361
- * - The integrations page wants a single table of "every broker"
46362
- * across kinds; a unified cap drives it without join logic.
46363
- * - Generic admin operations (add / remove / test / status) are
46364
- * identical across kinds — duplicating them per cap was busywork.
46365
- * - The `network-access` cap precedent: same interface, many
46366
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
46367
- *
46368
- * What stays kind-specific:
46369
- * - `getBrokerConfig` payload (kind decides whether it returns
46370
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
46371
- * `Record<string, unknown>` at the wire; consumers narrow.
46372
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
46373
- * key) — also typed as `Record<string, unknown>` so each kind can
46374
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
46375
- * without rebreaking the cap signature.
46376
- * - `add` `settings` payload (different fields per kind, validated by
46377
- * the kind-specific provider).
46378
- *
46379
- * Bidirectionality:
46380
- * - `publish` is RPC — synchronous result (provider-defined).
46381
- * - `subscribe` returns a subscription handle; the actual message
46382
- * stream flows over the typed event-bus as `broker.message` events
46383
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
46384
- * event handler. Subscriptions persist across reconnects — the
46385
- * provider re-subscribes upstream after a transport drop.
46386
- *
46387
- * Why event-bus push (not a subscription RPC stream):
46388
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
46389
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
46390
- * drop is recoverable via `getState({key})`).
46391
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
46392
- * - Cross-process: events already route through `$event-bus`; no
46393
- * per-broker wire-shaping needed.
46394
- */
46395
- var BrokerStatusEnum = _enum([
46719
+ _enum([
46396
46720
  "connected",
46397
46721
  "disconnected",
46398
46722
  "connecting",
@@ -46400,141 +46724,12 @@ var BrokerStatusEnum = _enum([
46400
46724
  "unreachable",
46401
46725
  "error"
46402
46726
  ]);
46403
- var BrokerInfoSchema = object({
46404
- /** Stable broker id. Persisted; survives addon restarts. */
46405
- id: string(),
46406
- /** Addon id of the provider that OWNS this broker.
46407
- *
46408
- * The `broker` cap is a system-scoped collection: several addons
46409
- * register a `broker` provider, each owning a DISJOINT set of
46410
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
46411
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
46412
- * device belongs to one integration. The admin UI threads this id
46413
- * back as the `{ addonId }` system-collection selector on every
46414
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
46415
- * `testConnection`), so the call routes to the OWNING provider
46416
- * instead of defaulting to the first-registered one. */
46417
- addonId: string(),
46418
- /** Human-readable name (operator-chosen at add-time). */
46419
- name: string(),
46420
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
46421
- kind: string(),
46422
- status: BrokerStatusEnum,
46423
- /** Free-form provider-specific info (HA version, MQTT broker
46424
- * flavour, latency, mTLS active, …). */
46425
- info: record(string(), unknown()),
46426
- /** Ms epoch of the last connection probe / status update. */
46427
- lastCheckedAt: number().nullable(),
46428
- /** Last error message, when `status` indicates failure. */
46429
- error: string().nullable()
46430
- });
46431
46727
  var RegistryStatusSchema = object({
46432
46728
  brokerCount: number().int().nonnegative(),
46433
46729
  connectedCount: number().int().nonnegative()
46434
46730
  });
46435
- /**
46436
- * One entry per `broker` provider — which addon provides which broker
46437
- * kind(s). The unified create picker reads this to know, for each
46438
- * (addonId, kind) pair the operator can pick, where to route the
46439
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
46440
- * `{ addonId }` selector). A provider only advertises a kind here when
46441
- * it implements `getSettingsSchema` for that kind (so the picker never
46442
- * offers a kind whose creation form can't be rendered).
46443
- */
46444
- var BrokerProviderInfoSchema = object({
46445
- /** Addon id of the `broker` provider this entry describes. */
46446
- addonId: string(),
46447
- /** Broker kinds this provider can create, with a display label. */
46448
- kinds: array(object({
46449
- kind: string(),
46450
- label: string(),
46451
- /**
46452
- * Relative hub path to start an interactive account link (OAuth popup).
46453
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
46454
- */
46455
- interactiveConnectPath: string().min(1).optional(),
46456
- /** Relative hub path to disconnect the linked account (same popup pattern). */
46457
- interactiveDisconnectPath: string().min(1).optional(),
46458
- /**
46459
- * The kind signs in through a server-held interactive session instead of
46460
- * (or before) typed credentials. `basePath` is a hub-relative route set
46461
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
46462
- * contract: `POST {basePath}/start` (body: the form's settings) answers
46463
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
46464
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
46465
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
46466
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
46467
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
46468
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
46469
- * offers it as the default path; the fields the session fills are
46470
- * marked `filledBySignIn` in the kind's settings schema.
46471
- *
46472
- * `methods` lists the ways the session can sign in, recommended first:
46473
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
46474
- * settings) answering `{ sessionId, userCode, verificationUrl,
46475
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
46476
- * any device, and the same `status` / `commit` / `cancel` routes follow
46477
- * (status then carries `method`, `userCode`, `verificationUrl`,
46478
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
46479
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
46480
- * `['proxy']`.
46481
- */
46482
- signIn: object({
46483
- basePath: string().min(1),
46484
- methods: array(_enum(["device-code", "proxy"])).optional()
46485
- }).optional()
46486
- }))
46487
- });
46488
- var ListInputSchema = object({
46489
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
46490
- * only HA brokers. Omit to list every broker. */
46491
- kind: string().optional() });
46492
46731
  var GetInputSchema = object({ id: string() });
46493
- var AddInputSchema = object({
46494
- kind: string().min(1),
46495
- name: string().min(1),
46496
- /**
46497
- * ADOPT an existing id instead of minting a new one.
46498
- *
46499
- * Written the day this cost an outage. A broker's id is not a detail: HA
46500
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
46501
- * lost from config and re-added as `ha_001` leaves every one of its devices
46502
- * bound to a broker that no longer exists. Re-entering the password under the
46503
- * ORIGINAL id turns a multi-step device migration back into re-entering a
46504
- * password.
46505
- *
46506
- * A provider MUST refuse an id that is already in use — adopting a live
46507
- * broker's id would silently take it over.
46508
- */
46509
- id: string().min(1).optional(),
46510
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
46511
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
46512
- * branch on receipt — invalid shape rejects the add. */
46513
- settings: record(string(), unknown())
46514
- });
46515
- var AddResultSchema = object({ id: string() });
46516
- var RemoveInputSchema = object({ id: string() });
46517
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
46518
- ok: literal(true),
46519
- latencyMs: number().nonnegative()
46520
- }), object({
46521
- ok: literal(false),
46522
- error: string()
46523
- })]);
46524
46732
  var SettingsRecordSchema$1 = record(string(), unknown());
46525
- var SettingsSchemaInputSchema = object({ kind: string() });
46526
- var TestSettingsInputSchema = object({
46527
- kind: string(),
46528
- settings: SettingsRecordSchema$1
46529
- });
46530
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
46531
- ok: literal(true),
46532
- latencyMs: number().nonnegative().optional()
46533
- }).strict(), object({
46534
- ok: literal(false),
46535
- error: string()
46536
- })]);
46537
- var SettingsSchemaResultSchema = unknown().nullable();
46538
46733
  var PublishInputSchema = object({
46539
46734
  brokerId: string(),
46540
46735
  /** Kind-specific routing target.
@@ -46578,51 +46773,12 @@ var brokerCapability = {
46578
46773
  kind: "poll"
46579
46774
  },
46580
46775
  methods: {
46581
- list: method(ListInputSchema, array(BrokerInfoSchema)),
46582
- get: method(GetInputSchema, BrokerInfoSchema.nullable()),
46583
- /** Enumerate which addon provides which broker kind(s) for the
46584
- * unified create picker. The auto-mount fans this array across
46585
- * every registered `broker` provider (array-output method), so the
46586
- * picker sees every kind from every provider in one call. */
46587
- listProviders: method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }),
46588
- add: method(AddInputSchema, AddResultSchema, {
46589
- kind: "mutation",
46590
- auth: "admin"
46591
- }),
46592
- remove: method(RemoveInputSchema, _void(), {
46593
- kind: "mutation",
46594
- auth: "admin"
46595
- }),
46596
- testConnection: method(GetInputSchema, TestConnectionResultSchema, {
46597
- kind: "mutation",
46598
- auth: "admin"
46599
- }),
46600
- /** Read the persisted settings record for a broker (kind-specific
46601
- * shape). Admin-only — settings may contain secrets. Returns `null`
46602
- * when the broker id is unknown to the provider (the collection
46603
- * fallback may route a foreign id to the first provider). */
46604
- getSettings: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46605
- /** Overwrite the persisted settings record. The kind-specific
46606
- * provider validates the shape and applies the change (reconnects
46607
- * if credentials changed). */
46608
- setSettings: method(object({
46609
- id: string(),
46610
- settings: SettingsRecordSchema$1
46611
- }), _void(), {
46612
- kind: "mutation",
46613
- auth: "admin"
46614
- }),
46615
46776
  /** Returns the kind-specific connection config the consumer needs
46616
46777
  * to open its own client (MQTT pattern: `{url, username, password,
46617
46778
  * clientIdPrefix}`). HA providers MAY return the auth envelope
46618
46779
  * but typical HA consumers use `publish` / `subscribe` instead.
46619
46780
  * Returns `null` when the broker id is unknown to the provider. */
46620
46781
  getBrokerConfig: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46621
- getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }),
46622
- testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, {
46623
- kind: "mutation",
46624
- auth: "admin"
46625
- }),
46626
46782
  publish: method(PublishInputSchema, unknown(), {
46627
46783
  kind: "mutation",
46628
46784
  auth: "admin"
@@ -48549,6 +48705,9 @@ var MediaPlayerStatusSchema = object({
48549
48705
  /** Repeat mode. Null when no repeat surface.
48550
48706
  * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48551
48707
  repeat: MediaPlayerRepeatSchema.nullable(),
48708
+ /** Ms epoch when `position` was read from the device. Null when the driver
48709
+ * does not say; a UI that advances the position while playing counts from it. */
48710
+ positionUpdatedAt: number().nullable().default(null),
48552
48711
  /** Ms epoch when the slice was last updated. */
48553
48712
  lastChangedAt: number()
48554
48713
  });
@@ -49128,7 +49287,9 @@ var ThresholdTransformDraftSchema = object({
49128
49287
  comparison: _enum(["gte", "lte"]),
49129
49288
  threshold: number(),
49130
49289
  startDwellMs: number().nonnegative(),
49131
- stopDwellMs: number().nonnegative()
49290
+ stopDwellMs: number().nonnegative(),
49291
+ /** Samples a start needs; absent = the compiler's default for the source (2 for running power, else 1). */
49292
+ minSamples: number().int().min(1).optional()
49132
49293
  });
49133
49294
  var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49134
49295
  IdentityTransformDraftSchema,
@@ -50695,7 +50856,14 @@ var DiscoveryCandidateSchema = object({
50695
50856
  /** `stableId` of the gateway candidate this device was found BEHIND. */
50696
50857
  parentStableId: string().optional(),
50697
50858
  /** `false` = shown for context but not pickable. Default true. */
50698
- selectable: boolean().optional()
50859
+ selectable: boolean().optional(),
50860
+ /**
50861
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
50862
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
50863
+ * admin asks for exactly these, on the creation form prefilled with
50864
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
50865
+ */
50866
+ needsParams: array(string()).optional()
50699
50867
  });
50700
50868
  /**
50701
50869
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -50754,12 +50922,24 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
50754
50922
  }), array(DiscoveryCandidateSchema), {
50755
50923
  kind: "mutation",
50756
50924
  auth: "admin"
50757
- }), method(object({}), CreationSchemaOutputSchema), method(object({}), object({ deviceType: _enum(DeviceType).nullable() })), method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
50925
+ }), method(object({}), CreationSchemaOutputSchema), method(object({
50926
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50927
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })), method(object({
50928
+ candidate: DiscoveryCandidateSchema,
50929
+ /** The integration the operator adopts into; a provider with several instances needs it. */
50930
+ integrationId: string().optional()
50931
+ }), DeviceSummarySchema, {
50758
50932
  kind: "mutation",
50759
50933
  auth: "admin"
50760
- }), method(object({}), boolean()), method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema), method(object({
50934
+ }), method(object({}), boolean()), method(object({
50761
50935
  type: _enum(DeviceType),
50762
- config: record(string(), unknown())
50936
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50937
+ integrationId: string().optional()
50938
+ }), CreationSchemaOutputSchema), method(object({
50939
+ type: _enum(DeviceType),
50940
+ config: record(string(), unknown()),
50941
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
50942
+ integrationId: string().optional()
50763
50943
  }), DeviceSummarySchema, {
50764
50944
  kind: "mutation",
50765
50945
  auth: "admin"
@@ -51469,7 +51649,10 @@ method(object({
51469
51649
  auth: "admin"
51470
51650
  }), method(object({
51471
51651
  addonId: string(),
51472
- type: _enum(DeviceType)
51652
+ type: _enum(DeviceType),
51653
+ /** The integration the form is for; a provider whose integrations differ (a hub
51654
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
51655
+ integrationId: string().optional()
51473
51656
  }), unknown().nullable()), method(object({
51474
51657
  addonId: string(),
51475
51658
  type: _enum(DeviceType),
@@ -51553,7 +51736,11 @@ method(object({
51553
51736
  kind: "mutation",
51554
51737
  auth: "admin",
51555
51738
  timeoutMs: 12e4
51556
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51739
+ }), method(object({
51740
+ addonId: string(),
51741
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
51742
+ integrationId: string().optional()
51743
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51557
51744
  deviceId: number(),
51558
51745
  key: string(),
51559
51746
  value: unknown()
@@ -54055,6 +54242,7 @@ var IntegrationWithStateSchema = object({
54055
54242
  id: string(),
54056
54243
  addonId: string(),
54057
54244
  name: string(),
54245
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54058
54246
  enabled: boolean(),
54059
54247
  info: record(string(), unknown()).readonly(),
54060
54248
  /** The discovery candidate this integration was set up from (D984). */
@@ -54067,6 +54255,7 @@ var IntegrationLiteSchema = object({
54067
54255
  id: string(),
54068
54256
  addonId: string(),
54069
54257
  name: string(),
54258
+ /** A projection of the instance body's switch (`setInstanceEnabled` is the only writer). */
54070
54259
  enabled: boolean(),
54071
54260
  info: record(string(), unknown()).readonly(),
54072
54261
  /** The discovery candidate this integration was set up from (D984). */
@@ -54149,7 +54338,7 @@ var TestConnectionStatusEnum = _enum([
54149
54338
  "inconclusive",
54150
54339
  "unsupported"
54151
54340
  ]);
54152
- var TestConnectionResultSchema$1 = object({
54341
+ var TestConnectionResultSchema = object({
54153
54342
  /** True ONLY for `validated`. Never true for a test that did not run. */
54154
54343
  success: boolean(),
54155
54344
  error: string().optional(),
@@ -54166,7 +54355,6 @@ var TestConnectionResultSchema$1 = object({
54166
54355
  var CreateIntegrationInputSchema = object({
54167
54356
  addonId: string(),
54168
54357
  name: string(),
54169
- enabled: boolean().optional(),
54170
54358
  info: record(string(), unknown()).optional(),
54171
54359
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54172
54360
  originStableId: string().optional(),
@@ -54175,6 +54363,11 @@ var CreateIntegrationInputSchema = object({
54175
54363
  var UpdateIntegrationInputSchema = object({
54176
54364
  id: string(),
54177
54365
  name: string().optional(),
54366
+ /**
54367
+ * Accepted for a FIXED builtin only (`info.fixed`: alarm panel, camera grid, core blocks,
54368
+ * terminal), which keeps no instance record: the registry flag is its one store. Any other
54369
+ * integration is switched through `integration-instances.setInstanceEnabled`.
54370
+ */
54178
54371
  enabled: boolean().optional(),
54179
54372
  info: record(string(), unknown()).optional()
54180
54373
  });
@@ -54194,7 +54387,7 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54194
54387
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54195
54388
  addonId: string(),
54196
54389
  settings: record(string(), unknown())
54197
- }), TestConnectionResultSchema$1, {
54390
+ }), TestConnectionResultSchema, {
54198
54391
  kind: "mutation",
54199
54392
  auth: "admin"
54200
54393
  });
@@ -54221,6 +54414,14 @@ var ConfigSchemaPassthrough$3 = custom();
54221
54414
  var IntegrationInstanceIdSchema = string().min(1);
54222
54415
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54223
54416
  /**
54417
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54418
+ * instance is an integration that brings devices (its record body owns the on/off switch);
54419
+ * `services`: a connection configured from the addon's own function page, never listed on
54420
+ * Integrations.
54421
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
54422
+ */
54423
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
54424
+ /**
54224
54425
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54225
54426
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54226
54427
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -54231,6 +54432,22 @@ var IntegrationInstanceKindSchema = object({
54231
54432
  /** Stable id of the kind, sent back as `createInstance.kind`. */
54232
54433
  id: string().min(1),
54233
54434
  label: string().min(1),
54435
+ /**
54436
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
54437
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
54438
+ * provider with more than one section must name it on every kind.
54439
+ */
54440
+ functionCap: string().min(1),
54441
+ /**
54442
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
54443
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
54444
+ * finds the instances whose kind names it; absent takes the kind `id`.
54445
+ */
54446
+ brokerKind: string().min(1).optional(),
54447
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
54448
+ role: IntegrationInstanceRoleSchema.optional(),
54449
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
54450
+ canTest: boolean().optional(),
54234
54451
  /** The kind signs in through a server-held interactive session. */
54235
54452
  signIn: object({
54236
54453
  basePath: string().min(1),
@@ -54241,22 +54458,38 @@ var IntegrationInstanceKindSchema = object({
54241
54458
  /** Relative hub path to disconnect that account. */
54242
54459
  disconnectPath: string().min(1).optional()
54243
54460
  });
54461
+ /**
54462
+ * How devices of an instance are found. `none`: the operator adds them by hand; `lan`: the addon
54463
+ * scans the network before any instance exists (the wizard offers the candidates); `account`: the
54464
+ * devices appear after the instance signs in. `scopedToInstance`: a discovery run belongs to ONE
54465
+ * instance and its candidates are claimed by it.
54466
+ */
54467
+ var IntegrationInstanceDiscoverySchema = object({
54468
+ mode: _enum([
54469
+ "none",
54470
+ "lan",
54471
+ "account"
54472
+ ]),
54473
+ scopedToInstance: boolean()
54474
+ });
54475
+ /**
54476
+ * One link a kind of this provider declares (D1013 rule 5): the body `field` of an instance of
54477
+ * `kind` holds the id of an instance of the function cap `to.cap` (of kind `to.kind`, when set).
54478
+ * The hub indexes these so the target's delete is refused while a link names it.
54479
+ */
54480
+ var IntegrationInstanceLinkSchema = object({
54481
+ kind: string().min(1),
54482
+ field: string().min(1),
54483
+ to: object({
54484
+ cap: string().min(1),
54485
+ kind: string().min(1).optional()
54486
+ })
54487
+ });
54244
54488
  var IntegrationInstanceDescriptionSchema = object({
54245
54489
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54246
- role: _enum([
54247
- "devices",
54248
- "services",
54249
- "both"
54250
- ]),
54490
+ role: IntegrationInstanceRoleSchema,
54251
54491
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54252
- discovery: object({
54253
- mode: _enum([
54254
- "none",
54255
- "lan",
54256
- "account"
54257
- ]),
54258
- scopedToInstance: boolean()
54259
- }).optional(),
54492
+ discovery: IntegrationInstanceDiscoverySchema.optional(),
54260
54493
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54261
54494
  instanceMode: IntegrationInstanceModeSchema,
54262
54495
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54277,7 +54510,9 @@ var IntegrationInstanceDescriptionSchema = object({
54277
54510
  * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
54278
54511
  * send an id (the UI then mints an opaque one).
54279
54512
  */
54280
- mintsId: boolean().optional()
54513
+ mintsId: boolean().optional(),
54514
+ /** The links to other instances the provider's kinds declare; absent means none. */
54515
+ links: array(IntegrationInstanceLinkSchema).optional()
54281
54516
  });
54282
54517
  var IntegrationInstanceStatusSchema = object({
54283
54518
  state: _enum([
@@ -54297,8 +54532,8 @@ var IntegrationInstanceSchema = object({
54297
54532
  configured: boolean(),
54298
54533
  /**
54299
54534
  * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
54300
- * so a row written before the field existed is on). Absent when the `integrations` registry
54301
- * owns the switch (`describe().role` is `devices`): read it from the registry row.
54535
+ * so a row written before the field existed is on). The same for every role, `devices` included:
54536
+ * the body is the one store, `setInstanceEnabled` the one writer (epic #440, step 3).
54302
54537
  */
54303
54538
  enabled: boolean().optional(),
54304
54539
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
@@ -54322,7 +54557,11 @@ var integrationInstancesCapability = {
54322
54557
  methods: {
54323
54558
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54324
54559
  /** The form; `id: null` is the create form. */
54325
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54560
+ instanceFormSchema: method(object({
54561
+ id: IntegrationInstanceIdSchema.nullable(),
54562
+ /** The kind of the create form (`id: null`) of a provider with several. */
54563
+ kind: string().min(1).optional()
54564
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54326
54565
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54327
54566
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54328
54567
  /**
@@ -54332,7 +54571,9 @@ var integrationInstancesCapability = {
54332
54571
  createInstance: method(object({
54333
54572
  id: IntegrationInstanceIdSchema.optional(),
54334
54573
  name: string().min(1),
54335
- kind: string().min(1).optional()
54574
+ kind: string().min(1).optional(),
54575
+ /** Form values written with the record (a link picked in the create dialog). */
54576
+ values: record(string(), unknown()).optional()
54336
54577
  }), object({ id: string() }), {
54337
54578
  kind: "mutation",
54338
54579
  auth: "admin"
@@ -54342,7 +54583,8 @@ var integrationInstancesCapability = {
54342
54583
  auth: "admin"
54343
54584
  }),
54344
54585
  /**
54345
- * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54586
+ * Switch ONE instance on or off, for every role; a missing record is created from the addon's
54587
+ * initial body. A row control, not a form field: `updateInstance.values` is the
54346
54588
  * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54347
54589
  */
54348
54590
  setInstanceEnabled: method(object({
@@ -54359,8 +54601,10 @@ var integrationInstancesCapability = {
54359
54601
  }),
54360
54602
  testInstance: optionalMethod(object({
54361
54603
  id: IntegrationInstanceIdSchema.nullable(),
54362
- values: record(string(), unknown())
54363
- }), TestConnectionResultSchema$1, {
54604
+ values: record(string(), unknown()),
54605
+ /** The kind to test when `id` is null and the provider has several. */
54606
+ kind: string().min(1).optional()
54607
+ }), TestConnectionResultSchema, {
54364
54608
  kind: "mutation",
54365
54609
  auth: "admin"
54366
54610
  })
@@ -56865,6 +57109,382 @@ var SystemMetricsSchema = object({
56865
57109
  gpuMemoryPercent: number().optional()
56866
57110
  });
56867
57111
  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);
57112
+ /**
57113
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
57114
+ * config documents, mirrors. The third storage API next to `ctx.settings`
57115
+ * (operator intent, D870) and device-history (numbers over time, D850).
57116
+ *
57117
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
57118
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
57119
+ * that with the addon id closed over). It is deliberately NOT in any input
57120
+ * schema, so a session can never supply it, and a call with no stamp is refused
57121
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
57122
+ * addons go through the owner's capability.
57123
+ *
57124
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
57125
+ * never `[]`. Secret fields are never on the wire: a read shows the
57126
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
57127
+ * resolves itself, and a write may carry only a keychain marker bound to the
57128
+ * row's own ref.
57129
+ *
57130
+ * Internal: addons reach it through `ctx.records`, never directly.
57131
+ */
57132
+ var RecordIdSchema = string().min(1).max(256);
57133
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
57134
+ var RecordBodySchema = record(string(), unknown());
57135
+ var RecordInputSchema = object({
57136
+ id: RecordIdSchema,
57137
+ /** The device this row belongs to (D865 removal, per-device reads). */
57138
+ deviceId: number().int().optional(),
57139
+ /** The domain clock, ms: observed / created / opened. */
57140
+ at: number().int().optional(),
57141
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
57142
+ expiresAt: number().int().optional(),
57143
+ data: RecordBodySchema
57144
+ });
57145
+ var RecordViewSchema = object({
57146
+ id: string(),
57147
+ deviceId: number().int().nullable(),
57148
+ at: number().nullable(),
57149
+ expiresAt: number().nullable(),
57150
+ rev: number().int(),
57151
+ updatedAt: number(),
57152
+ data: RecordBodySchema
57153
+ });
57154
+ /** Declared index fields only. Anything else does not compile, by design. */
57155
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
57156
+ string(),
57157
+ number(),
57158
+ boolean(),
57159
+ object({ in: array(union([
57160
+ string(),
57161
+ number(),
57162
+ boolean()
57163
+ ])).min(1).max(RECORD_BATCH_MAX) }),
57164
+ object({
57165
+ gt: union([string(), number()]).optional(),
57166
+ gte: union([string(), number()]).optional(),
57167
+ lt: union([string(), number()]).optional(),
57168
+ lte: union([string(), number()]).optional()
57169
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
57170
+ ]));
57171
+ var KindShape = { kind: RecordKindNameSchema };
57172
+ var TimeWindowShape = {
57173
+ deviceId: number().int().optional(),
57174
+ atFrom: number().optional(),
57175
+ atTo: number().optional()
57176
+ };
57177
+ var RecordQueryInputSchema = object({
57178
+ ...KindShape,
57179
+ ...TimeWindowShape,
57180
+ where: RecordWhereSchema.optional(),
57181
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
57182
+ order: _enum(["at", "id"]).optional(),
57183
+ desc: boolean().optional(),
57184
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
57185
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
57186
+ cursor: string().min(1).optional()
57187
+ });
57188
+ var RecordQueryResultSchema = object({
57189
+ records: array(RecordViewSchema),
57190
+ nextCursor: string().nullable()
57191
+ });
57192
+ var RecordKindStateSchema = _enum([
57193
+ "created",
57194
+ "unchanged",
57195
+ "updated"
57196
+ ]);
57197
+ var DeclareKindResultSchema = object({
57198
+ kindId: number().int(),
57199
+ state: RecordKindStateSchema,
57200
+ createdIndexes: array(string())
57201
+ });
57202
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
57203
+ var SecretRefsList = array(string());
57204
+ /**
57205
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
57206
+ * All ops of one call share ONE database file and ONE `transactFamily`.
57207
+ */
57208
+ var RecordTransactOpSchema = discriminatedUnion("op", [
57209
+ object({
57210
+ op: literal("put"),
57211
+ kind: RecordKindNameSchema,
57212
+ record: RecordInputSchema,
57213
+ ifRev: number().int().min(0).optional()
57214
+ }),
57215
+ object({
57216
+ op: literal("patch"),
57217
+ kind: RecordKindNameSchema,
57218
+ id: RecordIdSchema,
57219
+ data: RecordBodySchema,
57220
+ at: number().int().nullable().optional(),
57221
+ expiresAt: number().int().nullable().optional(),
57222
+ ifRev: number().int().min(1).optional()
57223
+ }),
57224
+ object({
57225
+ op: literal("delete"),
57226
+ kind: RecordKindNameSchema,
57227
+ id: RecordIdSchema
57228
+ })
57229
+ ]);
57230
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
57231
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
57232
+ kind: "mutation",
57233
+ auth: "admin"
57234
+ }), method(object({
57235
+ ...KindShape,
57236
+ id: RecordIdSchema
57237
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
57238
+ ...KindShape,
57239
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57240
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
57241
+ ...KindShape,
57242
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57243
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
57244
+ ...KindShape,
57245
+ record: RecordInputSchema,
57246
+ /** Compare-and-set. `0` means "the row must not exist". */
57247
+ ifRev: number().int().min(0).optional()
57248
+ }), object({
57249
+ rev: number().int(),
57250
+ releasedRefs: SecretRefsList
57251
+ }), {
57252
+ kind: "mutation",
57253
+ auth: "admin"
57254
+ }), method(object({
57255
+ ...KindShape,
57256
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
57257
+ }), object({
57258
+ count: number().int(),
57259
+ releasedRefs: SecretRefsList
57260
+ }), {
57261
+ kind: "mutation",
57262
+ auth: "admin"
57263
+ }), method(object({
57264
+ ...KindShape,
57265
+ id: RecordIdSchema,
57266
+ data: RecordBodySchema,
57267
+ at: number().int().nullable().optional(),
57268
+ expiresAt: number().int().nullable().optional(),
57269
+ ifRev: number().int().min(1).optional()
57270
+ }), object({
57271
+ rev: number().int(),
57272
+ releasedRefs: SecretRefsList
57273
+ }), {
57274
+ kind: "mutation",
57275
+ auth: "admin"
57276
+ }), method(object({
57277
+ ...KindShape,
57278
+ id: RecordIdSchema
57279
+ }), object({
57280
+ deleted: boolean(),
57281
+ secretRefs: SecretRefsList
57282
+ }), {
57283
+ kind: "mutation",
57284
+ auth: "admin"
57285
+ }), method(object({
57286
+ ...KindShape,
57287
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57288
+ }), object({
57289
+ deleted: number().int(),
57290
+ secretRefs: SecretRefsList
57291
+ }), {
57292
+ kind: "mutation",
57293
+ auth: "admin"
57294
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
57295
+ ...KindShape,
57296
+ ...TimeWindowShape,
57297
+ where: RecordWhereSchema.optional()
57298
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
57299
+ ...KindShape,
57300
+ deviceId: number().int().optional(),
57301
+ from: number(),
57302
+ to: number(),
57303
+ bucketMs: number().int().positive()
57304
+ }), object({ buckets: array(object({
57305
+ bucketStart: number(),
57306
+ count: number().int()
57307
+ })) }), { auth: "admin" }), method(object({
57308
+ ...KindShape,
57309
+ op: _enum([
57310
+ "sum",
57311
+ "min",
57312
+ "max",
57313
+ "count"
57314
+ ]),
57315
+ field: RecordFieldPathSchema.optional(),
57316
+ groupBy: RecordFieldPathSchema.optional(),
57317
+ where: RecordWhereSchema.optional()
57318
+ }), object({ rows: array(object({
57319
+ group: union([
57320
+ string(),
57321
+ number(),
57322
+ _null()
57323
+ ]),
57324
+ value: number().nullable()
57325
+ })) }), { auth: "admin" }), method(object({
57326
+ ...KindShape,
57327
+ deviceId: number().int().optional(),
57328
+ atBefore: number().optional(),
57329
+ where: RecordWhereSchema.optional()
57330
+ }), object({
57331
+ deleted: number().int(),
57332
+ secretRefs: SecretRefsList
57333
+ }), {
57334
+ kind: "mutation",
57335
+ auth: "admin"
57336
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
57337
+ results: array(object({
57338
+ rev: number().int().nullable(),
57339
+ deleted: boolean()
57340
+ })),
57341
+ releasedRefs: SecretRefsList,
57342
+ secretRefs: SecretRefsList
57343
+ }), {
57344
+ kind: "mutation",
57345
+ auth: "admin"
57346
+ }), method(object({
57347
+ deviceId: number().int(),
57348
+ kinds: array(RecordKindNameSchema).optional()
57349
+ }), object({
57350
+ deleted: record(string(), number().int()),
57351
+ secretRefs: SecretRefsList
57352
+ }), {
57353
+ kind: "mutation",
57354
+ auth: "admin"
57355
+ }), method(object(KindShape), object({ id: number().int() }), {
57356
+ kind: "mutation",
57357
+ auth: "admin"
57358
+ });
57359
+ /**
57360
+ * The wire shapes of the migration API, version 1 (planning#447).
57361
+ *
57362
+ * A migration is code that outlives the server it was written against: an addon at
57363
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
57364
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
57365
+ * is the contract of every method of it, one Zod pair per method.
57366
+ *
57367
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
57368
+ * field is never removed or made required, an enum never narrows, an output field is
57369
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
57370
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
57371
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
57372
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
57373
+ */
57374
+ var Rows = record(string(), unknown());
57375
+ var IntegrationId = object({ integrationId: string().min(1) });
57376
+ var RecordId = object({ id: string().min(1) });
57377
+ var RecordRowSchema = object({
57378
+ id: string(),
57379
+ deviceId: number().int().nullable(),
57380
+ at: number().nullable(),
57381
+ expiresAt: number().nullable(),
57382
+ rev: number().int(),
57383
+ updatedAt: number(),
57384
+ data: Rows
57385
+ });
57386
+ var RecordPutShape = {
57387
+ id: string().min(1),
57388
+ deviceId: number().int().optional(),
57389
+ at: number().int().optional(),
57390
+ expiresAt: number().int().optional(),
57391
+ data: Rows
57392
+ };
57393
+ var MigrationIntegrationSchema = object({
57394
+ id: string(),
57395
+ addonId: string(),
57396
+ name: string(),
57397
+ info: Rows,
57398
+ /** The registry's stored switch: read by the one-switch migration, nothing else. */
57399
+ enabled: boolean().optional(),
57400
+ originStableId: string().optional()
57401
+ });
57402
+ var MigrationDeviceSchema = object({
57403
+ id: number().int(),
57404
+ integrationId: string().nullable().optional(),
57405
+ /** The owning device; null or absent for a root. */
57406
+ parentDeviceId: number().int().nullable().optional(),
57407
+ type: string().optional(),
57408
+ name: string().optional(),
57409
+ stableId: string().optional()
57410
+ });
57411
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
57412
+ var MigrationApiInfoSchema = object({
57413
+ version: number().int(),
57414
+ methods: array(string())
57415
+ });
57416
+ object({
57417
+ message: string(),
57418
+ meta: Rows.optional(),
57419
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
57420
+ tags: object({ deviceId: number().int().optional() }).optional()
57421
+ });
57422
+ object({
57423
+ owner: string().min(1),
57424
+ metas: array(MigrationMetaSchema)
57425
+ }), object({
57426
+ bootId: string(),
57427
+ snapshot: _enum([
57428
+ "none",
57429
+ "written",
57430
+ "refused"
57431
+ ]),
57432
+ steps: array(MigrationOwnerStepSchema),
57433
+ /** The migration API the engine serves; absent from a server that predates it. */
57434
+ migrationApi: MigrationApiInfoSchema.optional()
57435
+ }), object({ id: string().min(1) }), object({
57436
+ proceed: boolean(),
57437
+ state: union([literal("pending"), MigrationStatusSchema]),
57438
+ reason: string().nullable()
57439
+ }), object({
57440
+ id: string().min(1),
57441
+ result: MigrationOwnerResultSchema
57442
+ }), object({
57443
+ status: MigrationStatusSchema,
57444
+ error: string().nullable(),
57445
+ rowsChanged: number().int().nonnegative()
57446
+ }), object({
57447
+ rows: number().int().nonnegative(),
57448
+ secrets: number().int().nonnegative()
57449
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
57450
+ present: boolean(),
57451
+ removed: Rows
57452
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
57453
+ ...RecordPutShape,
57454
+ ifRev: number().int().optional()
57455
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
57456
+ partial: Rows,
57457
+ ifRev: number().int().optional()
57458
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
57459
+ deviceId: number().int().optional(),
57460
+ atFrom: number().optional(),
57461
+ atTo: number().optional(),
57462
+ where: RecordWhereSchema.optional(),
57463
+ limit: number().int().min(1).optional(),
57464
+ cursor: string().min(1).optional(),
57465
+ resolveSecrets: boolean().optional()
57466
+ }), object({
57467
+ records: array(RecordRowSchema),
57468
+ nextCursor: string().nullable()
57469
+ }), object({
57470
+ deviceId: number().int().optional(),
57471
+ atBefore: number().optional(),
57472
+ where: RecordWhereSchema.optional()
57473
+ }), 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({
57474
+ ref: string().min(1),
57475
+ value: string()
57476
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
57477
+ addonId: string().min(1),
57478
+ integrationId: string().min(1).optional()
57479
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
57480
+ id: number().int(),
57481
+ integrationId: string().nullable(),
57482
+ /** Whether the device carries any stored config; its content is not offered. */
57483
+ hasConfig: boolean()
57484
+ }).nullable(), object({
57485
+ deviceId: number().int(),
57486
+ integrationId: string().min(1)
57487
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
56868
57488
  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({
56869
57489
  id: string().min(1),
56870
57490
  error: string().min(1)
@@ -56894,7 +57514,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
56894
57514
  "written",
56895
57515
  "refused"
56896
57516
  ]),
56897
- steps: array(MigrationOwnerStepSchema)
57517
+ steps: array(MigrationOwnerStepSchema),
57518
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
57519
+ migrationApi: MigrationApiInfoSchema.optional()
56898
57520
  }), {
56899
57521
  kind: "mutation",
56900
57522
  auth: "admin"
@@ -59561,7 +60183,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
59561
60183
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
59562
60184
  kind: "mutation",
59563
60185
  auth: "admin"
59564
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
60186
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
60187
+ kind: "query",
60188
+ auth: "admin"
60189
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
59565
60190
  kind: "query",
59566
60191
  auth: "admin"
59567
60192
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -61968,7 +62593,7 @@ var BrokerStatusSchema$1 = _enum([
61968
62593
  "unreachable",
61969
62594
  "tls-error"
61970
62595
  ]);
61971
- var BrokerInfoSchema$1 = object({
62596
+ var BrokerInfoSchema = object({
61972
62597
  id: string(),
61973
62598
  name: string(),
61974
62599
  url: string(),
@@ -62031,7 +62656,7 @@ var StatusSchema = object({
62031
62656
  brokerCount: number(),
62032
62657
  embeddedRunning: boolean()
62033
62658
  });
62034
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
62659
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
62035
62660
  kind: "mutation",
62036
62661
  auth: "admin"
62037
62662
  }), method(IdInputSchema, _void(), {
@@ -66290,14 +66915,6 @@ object({
66290
66915
  empty: boolean().nullable(),
66291
66916
  /** True while the pump is running. Null while unknown. */
66292
66917
  pumpRunning: boolean().nullable(),
66293
- /** Water drunk in the last drink, in litres. */
66294
- lastDrink: number().min(0).nullable().meta(readingMeta("volume")),
66295
- /** Water drunk in the current hour, in litres. */
66296
- currentHourDrink: number().min(0).nullable().meta(readingMeta("volume")),
66297
- /** Water drunk over the last 24 hours (rolling), in litres. */
66298
- last24hDrink: number().min(0).nullable().meta(readingMeta("volume")),
66299
- /** Water drunk since local midnight, in litres. Null when the fountain has no such sensor. */
66300
- todayDrink: number().min(0).nullable().meta(readingMeta("volume")),
66301
66918
  /** Decoded fault message. Null means healthy; a non-null string is an active fault. */
66302
66919
  error: string().nullable(),
66303
66920
  /** Ms epoch when the slice was last refreshed. */
@@ -66310,9 +66927,6 @@ DeviceType.PetFountain, method(object({
66310
66927
  }), _void(), {
66311
66928
  kind: "mutation",
66312
66929
  auth: "protected"
66313
- }), method(object({ deviceId: DeviceIdSchema$1 }), _void(), {
66314
- kind: "mutation",
66315
- auth: "protected"
66316
66930
  });
66317
66931
  /**
66318
66932
  * The wire shapes of the Auto tune plan and apply (D745), used by the
@@ -68349,253 +68963,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
68349
68963
  auth: "admin"
68350
68964
  });
68351
68965
  /**
68352
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
68353
- * config documents, mirrors. The third storage API next to `ctx.settings`
68354
- * (operator intent, D870) and device-history (numbers over time, D850).
68355
- *
68356
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
68357
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
68358
- * that with the addon id closed over). It is deliberately NOT in any input
68359
- * schema, so a session can never supply it, and a call with no stamp is refused
68360
- * `records/no-caller`. A kind is readable and writable only by its owner; other
68361
- * addons go through the owner's capability.
68362
- *
68363
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
68364
- * never `[]`. Secret fields are never on the wire: a read shows the
68365
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
68366
- * resolves itself, and a write may carry only a keychain marker bound to the
68367
- * row's own ref.
68368
- *
68369
- * Internal: addons reach it through `ctx.records`, never directly.
68370
- */
68371
- var RecordIdSchema = string().min(1).max(256);
68372
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
68373
- var RecordBodySchema = record(string(), unknown());
68374
- var RecordInputSchema = object({
68375
- id: RecordIdSchema,
68376
- /** The device this row belongs to (D865 removal, per-device reads). */
68377
- deviceId: number().int().optional(),
68378
- /** The domain clock, ms: observed / created / opened. */
68379
- at: number().int().optional(),
68380
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
68381
- expiresAt: number().int().optional(),
68382
- data: RecordBodySchema
68383
- });
68384
- var RecordViewSchema = object({
68385
- id: string(),
68386
- deviceId: number().int().nullable(),
68387
- at: number().nullable(),
68388
- expiresAt: number().nullable(),
68389
- rev: number().int(),
68390
- updatedAt: number(),
68391
- data: RecordBodySchema
68392
- });
68393
- /** Declared index fields only. Anything else does not compile, by design. */
68394
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
68395
- string(),
68396
- number(),
68397
- boolean(),
68398
- object({ in: array(union([
68399
- string(),
68400
- number(),
68401
- boolean()
68402
- ])).min(1).max(RECORD_BATCH_MAX) }),
68403
- object({
68404
- gt: union([string(), number()]).optional(),
68405
- gte: union([string(), number()]).optional(),
68406
- lt: union([string(), number()]).optional(),
68407
- lte: union([string(), number()]).optional()
68408
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
68409
- ]));
68410
- var KindShape = { kind: RecordKindNameSchema };
68411
- var TimeWindowShape = {
68412
- deviceId: number().int().optional(),
68413
- atFrom: number().optional(),
68414
- atTo: number().optional()
68415
- };
68416
- var RecordQueryInputSchema = object({
68417
- ...KindShape,
68418
- ...TimeWindowShape,
68419
- where: RecordWhereSchema.optional(),
68420
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
68421
- order: _enum(["at", "id"]).optional(),
68422
- desc: boolean().optional(),
68423
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
68424
- /** Opaque keyset cursor from a previous answer. There is no offset. */
68425
- cursor: string().min(1).optional()
68426
- });
68427
- var RecordQueryResultSchema = object({
68428
- records: array(RecordViewSchema),
68429
- nextCursor: string().nullable()
68430
- });
68431
- var RecordKindStateSchema = _enum([
68432
- "created",
68433
- "unchanged",
68434
- "updated"
68435
- ]);
68436
- var DeclareKindResultSchema = object({
68437
- kindId: number().int(),
68438
- state: RecordKindStateSchema,
68439
- createdIndexes: array(string())
68440
- });
68441
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
68442
- var SecretRefsList = array(string());
68443
- /**
68444
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
68445
- * All ops of one call share ONE database file and ONE `transactFamily`.
68446
- */
68447
- var RecordTransactOpSchema = discriminatedUnion("op", [
68448
- object({
68449
- op: literal("put"),
68450
- kind: RecordKindNameSchema,
68451
- record: RecordInputSchema,
68452
- ifRev: number().int().min(0).optional()
68453
- }),
68454
- object({
68455
- op: literal("patch"),
68456
- kind: RecordKindNameSchema,
68457
- id: RecordIdSchema,
68458
- data: RecordBodySchema,
68459
- at: number().int().nullable().optional(),
68460
- expiresAt: number().int().nullable().optional(),
68461
- ifRev: number().int().min(1).optional()
68462
- }),
68463
- object({
68464
- op: literal("delete"),
68465
- kind: RecordKindNameSchema,
68466
- id: RecordIdSchema
68467
- })
68468
- ]);
68469
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
68470
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
68471
- kind: "mutation",
68472
- auth: "admin"
68473
- }), method(object({
68474
- ...KindShape,
68475
- id: RecordIdSchema
68476
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
68477
- ...KindShape,
68478
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68479
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
68480
- ...KindShape,
68481
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68482
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
68483
- ...KindShape,
68484
- record: RecordInputSchema,
68485
- /** Compare-and-set. `0` means "the row must not exist". */
68486
- ifRev: number().int().min(0).optional()
68487
- }), object({
68488
- rev: number().int(),
68489
- releasedRefs: SecretRefsList
68490
- }), {
68491
- kind: "mutation",
68492
- auth: "admin"
68493
- }), method(object({
68494
- ...KindShape,
68495
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
68496
- }), object({
68497
- count: number().int(),
68498
- releasedRefs: SecretRefsList
68499
- }), {
68500
- kind: "mutation",
68501
- auth: "admin"
68502
- }), method(object({
68503
- ...KindShape,
68504
- id: RecordIdSchema,
68505
- data: RecordBodySchema,
68506
- at: number().int().nullable().optional(),
68507
- expiresAt: number().int().nullable().optional(),
68508
- ifRev: number().int().min(1).optional()
68509
- }), object({
68510
- rev: number().int(),
68511
- releasedRefs: SecretRefsList
68512
- }), {
68513
- kind: "mutation",
68514
- auth: "admin"
68515
- }), method(object({
68516
- ...KindShape,
68517
- id: RecordIdSchema
68518
- }), object({
68519
- deleted: boolean(),
68520
- secretRefs: SecretRefsList
68521
- }), {
68522
- kind: "mutation",
68523
- auth: "admin"
68524
- }), method(object({
68525
- ...KindShape,
68526
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68527
- }), object({
68528
- deleted: number().int(),
68529
- secretRefs: SecretRefsList
68530
- }), {
68531
- kind: "mutation",
68532
- auth: "admin"
68533
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
68534
- ...KindShape,
68535
- ...TimeWindowShape,
68536
- where: RecordWhereSchema.optional()
68537
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
68538
- ...KindShape,
68539
- deviceId: number().int().optional(),
68540
- from: number(),
68541
- to: number(),
68542
- bucketMs: number().int().positive()
68543
- }), object({ buckets: array(object({
68544
- bucketStart: number(),
68545
- count: number().int()
68546
- })) }), { auth: "admin" }), method(object({
68547
- ...KindShape,
68548
- op: _enum([
68549
- "sum",
68550
- "min",
68551
- "max",
68552
- "count"
68553
- ]),
68554
- field: RecordFieldPathSchema.optional(),
68555
- groupBy: RecordFieldPathSchema.optional(),
68556
- where: RecordWhereSchema.optional()
68557
- }), object({ rows: array(object({
68558
- group: union([
68559
- string(),
68560
- number(),
68561
- _null()
68562
- ]),
68563
- value: number().nullable()
68564
- })) }), { auth: "admin" }), method(object({
68565
- ...KindShape,
68566
- deviceId: number().int().optional(),
68567
- atBefore: number().optional(),
68568
- where: RecordWhereSchema.optional()
68569
- }), object({
68570
- deleted: number().int(),
68571
- secretRefs: SecretRefsList
68572
- }), {
68573
- kind: "mutation",
68574
- auth: "admin"
68575
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
68576
- results: array(object({
68577
- rev: number().int().nullable(),
68578
- deleted: boolean()
68579
- })),
68580
- releasedRefs: SecretRefsList,
68581
- secretRefs: SecretRefsList
68582
- }), {
68583
- kind: "mutation",
68584
- auth: "admin"
68585
- }), method(object({
68586
- deviceId: number().int(),
68587
- kinds: array(RecordKindNameSchema).optional()
68588
- }), object({
68589
- deleted: record(string(), number().int()),
68590
- secretRefs: SecretRefsList
68591
- }), {
68592
- kind: "mutation",
68593
- auth: "admin"
68594
- }), method(object(KindShape), object({ id: number().int() }), {
68595
- kind: "mutation",
68596
- auth: "admin"
68597
- });
68598
- /**
68599
68966
  * record-entries - the ONE admin surface for every list of user-created entries
68600
68967
  * (D881): notification targets, brokers, LLM profiles, anything an addon
68601
68968
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -77151,20 +77518,6 @@ Object.freeze({
77151
77518
  access: "create",
77152
77519
  role: "viewer"
77153
77520
  },
77154
- "broker.add": {
77155
- capName: "broker",
77156
- capScope: "system",
77157
- addonId: null,
77158
- access: "create",
77159
- role: "admin"
77160
- },
77161
- "broker.get": {
77162
- capName: "broker",
77163
- capScope: "system",
77164
- addonId: null,
77165
- access: "view",
77166
- role: "admin"
77167
- },
77168
77521
  "broker.getBrokerConfig": {
77169
77522
  capName: "broker",
77170
77523
  capScope: "system",
@@ -77172,20 +77525,6 @@ Object.freeze({
77172
77525
  access: "view",
77173
77526
  role: "admin"
77174
77527
  },
77175
- "broker.getSettings": {
77176
- capName: "broker",
77177
- capScope: "system",
77178
- addonId: null,
77179
- access: "view",
77180
- role: "admin"
77181
- },
77182
- "broker.getSettingsSchema": {
77183
- capName: "broker",
77184
- capScope: "system",
77185
- addonId: null,
77186
- access: "view",
77187
- role: "admin"
77188
- },
77189
77528
  "broker.getState": {
77190
77529
  capName: "broker",
77191
77530
  capScope: "system",
@@ -77200,20 +77539,6 @@ Object.freeze({
77200
77539
  access: "view",
77201
77540
  role: "admin"
77202
77541
  },
77203
- "broker.list": {
77204
- capName: "broker",
77205
- capScope: "system",
77206
- addonId: null,
77207
- access: "view",
77208
- role: "admin"
77209
- },
77210
- "broker.listProviders": {
77211
- capName: "broker",
77212
- capScope: "system",
77213
- addonId: null,
77214
- access: "view",
77215
- role: "admin"
77216
- },
77217
77542
  "broker.publish": {
77218
77543
  capName: "broker",
77219
77544
  capScope: "system",
@@ -77221,20 +77546,6 @@ Object.freeze({
77221
77546
  access: "create",
77222
77547
  role: "admin"
77223
77548
  },
77224
- "broker.remove": {
77225
- capName: "broker",
77226
- capScope: "system",
77227
- addonId: null,
77228
- access: "delete",
77229
- role: "admin"
77230
- },
77231
- "broker.setSettings": {
77232
- capName: "broker",
77233
- capScope: "system",
77234
- addonId: null,
77235
- access: "create",
77236
- role: "admin"
77237
- },
77238
77549
  "broker.subscribe": {
77239
77550
  capName: "broker",
77240
77551
  capScope: "system",
@@ -77242,20 +77553,6 @@ Object.freeze({
77242
77553
  access: "create",
77243
77554
  role: "admin"
77244
77555
  },
77245
- "broker.testConnection": {
77246
- capName: "broker",
77247
- capScope: "system",
77248
- addonId: null,
77249
- access: "create",
77250
- role: "admin"
77251
- },
77252
- "broker.testSettings": {
77253
- capName: "broker",
77254
- capScope: "system",
77255
- addonId: null,
77256
- access: "create",
77257
- role: "admin"
77258
- },
77259
77556
  "broker.unsubscribe": {
77260
77557
  capName: "broker",
77261
77558
  capScope: "system",
@@ -82016,13 +82313,6 @@ Object.freeze({
82016
82313
  access: "view",
82017
82314
  role: "viewer"
82018
82315
  },
82019
- "petFountain.resetDailyConsumption": {
82020
- capName: "pet-fountain",
82021
- capScope: "device",
82022
- addonId: null,
82023
- access: "delete",
82024
- role: "viewer"
82025
- },
82026
82316
  "petFountain.setPump": {
82027
82317
  capName: "pet-fountain",
82028
82318
  capScope: "device",
@@ -82219,6 +82509,13 @@ Object.freeze({
82219
82509
  access: "view",
82220
82510
  role: "viewer"
82221
82511
  },
82512
+ "pipelineAnalytics.getMediaLocationCensus": {
82513
+ capName: "pipeline-analytics",
82514
+ capScope: "device",
82515
+ addonId: null,
82516
+ access: "view",
82517
+ role: "admin"
82518
+ },
82222
82519
  "pipelineAnalytics.getMediaReclaimStatus": {
82223
82520
  capName: "pipeline-analytics",
82224
82521
  capScope: "device",
@@ -88412,11 +88709,6 @@ Object.freeze({
88412
88709
  form: "single",
88413
88710
  optional: false
88414
88711
  }],
88415
- "petFountain.resetDailyConsumption": [{
88416
- name: "deviceId",
88417
- form: "single",
88418
- optional: false
88419
- }],
88420
88712
  "petFountain.setPump": [{
88421
88713
  name: "deviceId",
88422
88714
  form: "single",
@@ -91160,6 +91452,22 @@ object({
91160
91452
  delay: number().nonnegative().optional(),
91161
91453
  commands: record(string(), unknown())
91162
91454
  });
91455
+ var InstanceInUseError = class extends Error {
91456
+ instanceId;
91457
+ users;
91458
+ name = "InstanceInUseError";
91459
+ constructor(instanceId, users) {
91460
+ super(`instance '${instanceId}' is still in use by ${users.map((u) => `${u.kind} '${u.name ?? u.id}' (${u.id})`).join(", ")}; unlink them first`);
91461
+ this.instanceId = instanceId;
91462
+ this.users = users;
91463
+ }
91464
+ };
91465
+ /** Throw {@link InstanceInUseError} when any finder names a user of `instanceId`. */
91466
+ async function assertInstanceUnused(instanceId, finders) {
91467
+ const users = [];
91468
+ for (const finder of finders) users.push(...await finder.find(instanceId));
91469
+ if (users.length > 0) throw new InstanceInUseError(instanceId, users);
91470
+ }
91163
91471
  //#endregion
91164
91472
  //#region src/relay-record-kinds.ts
91165
91473
  /**
@@ -91409,29 +91717,6 @@ var MessageRing = class {
91409
91717
  }
91410
91718
  };
91411
91719
  //#endregion
91412
- //#region src/mailbox-record-kinds.ts
91413
- /**
91414
- * The `smtp-inbound` mailbox as a record (D999): one `mailboxes` row per mailbox, owned by
91415
- * `smtp-nodemailer`. The row id is the broker id. The SMTP AUTH password is a keychain-bound secret
91416
- * field; nothing else holds a copy.
91417
- */
91418
- var MailboxBodySchema = entryBody({
91419
- port: number().int().min(1).max(65535),
91420
- bindHost: string().min(1),
91421
- domain: string().min(1),
91422
- requireAuth: boolean(),
91423
- username: string(),
91424
- password: string().optional().meta({ secret: true }),
91425
- starttls: boolean(),
91426
- maxMessageBytes: number().int().positive()
91427
- });
91428
- var mailboxesKind = defineEntryKind("mailboxes", {
91429
- title: "Inbound mailboxes",
91430
- nameField: "name",
91431
- schema: MailboxBodySchema,
91432
- writeTrigger: "an operator (or a consumer addon, once) adds or edits an inbound mailbox"
91433
- });
91434
- //#endregion
91435
91720
  //#region src/inbound-broker.ts
91436
91721
  /**
91437
91722
  * The `smtp-inbound` broker kind (D999): a mailbox a device can send alarm mail to.
@@ -91445,7 +91730,6 @@ var mailboxesKind = defineEntryKind("mailboxes", {
91445
91730
  var REBIND_DELAY_MS = 5e3;
91446
91731
  var MAX_REBIND_ATTEMPTS = 6;
91447
91732
  var NO_INTERNAL_HOST_REASON = "The hub has no internal address. Flag one as \"Internal\" under System → Network; cameras need it to reach this mailbox.";
91448
- var KIND_LABEL = "Inbound mailbox (SMTP)";
91449
91733
  var PAGE = 500;
91450
91734
  /** The hostname of a role's resolved base URL (`http://192.0.2.10:4480` → `192.0.2.10`). */
91451
91735
  function hostFromRole(resolved) {
@@ -91518,6 +91802,20 @@ var SmtpInboundBroker = class {
91518
91802
  this.rebindTimers.clear();
91519
91803
  await Promise.all([...this.runtimes.keys()].map((id) => this.unbind(id)));
91520
91804
  }
91805
+ /** Bring the listener in line with the record after the instances page changed it. */
91806
+ reconcileMailbox(id) {
91807
+ return this.reconcile(id);
91808
+ }
91809
+ /** The runtime's view of one mailbox; null while it has no listener. */
91810
+ runtimeOf(id) {
91811
+ const runtime = this.runtimes.get(id);
91812
+ if (runtime === void 0) return null;
91813
+ return {
91814
+ status: runtime.status,
91815
+ error: runtime.error,
91816
+ checkedAt: runtime.checkedAt
91817
+ };
91818
+ }
91521
91819
  reconcile(id) {
91522
91820
  const next = (this.chains.get(id) ?? Promise.resolve()).then(() => this.applyRecord(id));
91523
91821
  this.chains.set(id, next.catch(() => void 0));
@@ -91635,28 +91933,6 @@ var SmtpInboundBroker = class {
91635
91933
  payload: message
91636
91934
  });
91637
91935
  }
91638
- async exists(id) {
91639
- return await this.deps.handle.get(id) !== null;
91640
- }
91641
- async info(id) {
91642
- const row = await this.deps.handle.get(id);
91643
- if (row === null) return null;
91644
- const runtime = this.runtimes.get(id);
91645
- return {
91646
- id,
91647
- addonId: this.deps.addonId,
91648
- name: row.data.name,
91649
- kind: SMTP_INBOUND_KIND,
91650
- status: runtime?.status ?? "disconnected",
91651
- info: {
91652
- port: row.data.port,
91653
- domain: row.data.domain,
91654
- recipients: runtime === void 0 ? 0 : [...runtime.subscriptions.values()].reduce((n, s) => n + s.recipients.size, 0)
91655
- },
91656
- lastCheckedAt: runtime?.checkedAt ?? null,
91657
- error: runtime?.error ?? null
91658
- };
91659
- }
91660
91936
  async subscribe(brokerId, filter) {
91661
91937
  const parsed = SmtpInboundFilterSchema.parse(filter);
91662
91938
  const runtime = this.runtimes.get(brokerId);
@@ -91676,85 +91952,19 @@ var SmtpInboundBroker = class {
91676
91952
  runtime.subscriptions = next;
91677
91953
  return { subscriptionId: id };
91678
91954
  }
91955
+ /** The subscribers (camera email push) that still read one mailbox. */
91956
+ subscriberUsers() {
91957
+ return { find: async (brokerId) => [...this.runtimes.get(brokerId)?.subscriptions.values() ?? []].map((sub) => ({
91958
+ kind: "subscriber",
91959
+ id: sub.subscriberId
91960
+ })) };
91961
+ }
91962
+ /**
91963
+ * The `broker` cap is the bus only (D1013): the mailboxes themselves are the `mailboxes` kind of
91964
+ * the addon's `integration-instances` provider (`mailbox-instances.ts`).
91965
+ */
91679
91966
  provider() {
91680
- const owns = (id) => this.exists(id);
91681
91967
  return {
91682
- list: async ({ kind }) => {
91683
- if (kind !== void 0 && kind !== "smtp-inbound") return [];
91684
- const page = await this.deps.handle.query({ limit: PAGE });
91685
- return (await Promise.all(page.records.map((r) => this.info(r.id)))).flatMap((i) => i === null ? [] : [i]);
91686
- },
91687
- get: async ({ id }) => this.info(id),
91688
- listProviders: async () => [{
91689
- addonId: this.deps.addonId,
91690
- kinds: [{
91691
- kind: SMTP_INBOUND_KIND,
91692
- label: KIND_LABEL
91693
- }]
91694
- }],
91695
- add: async ({ kind, name, id, settings }) => {
91696
- if (kind !== "smtp-inbound") throw new Error(`smtp-nodemailer: only kind '${SMTP_INBOUND_KIND}' is handled here (got '${kind}')`);
91697
- const parsed = SmtpInboundSettingsSchema.parse(settings);
91698
- const brokerId = id ?? `smtp-inbound-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
91699
- if (await this.exists(brokerId)) throw new Error(`broker id '${brokerId}' is already in use`);
91700
- const body = MailboxBodySchema.parse({
91701
- name,
91702
- port: parsed.port,
91703
- bindHost: parsed.bindHost,
91704
- domain: parsed.domain,
91705
- requireAuth: parsed.requireAuth,
91706
- username: parsed.username.length > 0 ? parsed.username : `camstack-${(0, node_crypto.randomBytes)(4).toString("hex")}`,
91707
- password: parsed.password.length > 0 ? parsed.password : (0, node_crypto.randomBytes)(18).toString("base64url"),
91708
- starttls: parsed.starttls,
91709
- maxMessageBytes: parsed.maxMessageBytes
91710
- });
91711
- await this.deps.handle.put({
91712
- id: brokerId,
91713
- data: body
91714
- }, { ifRev: 0 });
91715
- await this.reconcile(brokerId);
91716
- return { id: brokerId };
91717
- },
91718
- remove: async ({ id }) => {
91719
- if (!await owns(id)) return;
91720
- await this.deps.handle.delete(id);
91721
- await this.reconcile(id);
91722
- },
91723
- testConnection: async ({ id }) => {
91724
- if (!await owns(id)) return {
91725
- ok: false,
91726
- error: "unknown broker"
91727
- };
91728
- const runtime = this.runtimes.get(id);
91729
- if (runtime?.status === "connected") return {
91730
- ok: true,
91731
- latencyMs: 0
91732
- };
91733
- return {
91734
- ok: false,
91735
- error: runtime?.error ?? "The mailbox is not listening"
91736
- };
91737
- },
91738
- getSettings: async ({ id }) => {
91739
- const row = await this.deps.handle.get(id);
91740
- if (row === null) return null;
91741
- const { name: _name, password: _password, ...settings } = row.data;
91742
- return settings;
91743
- },
91744
- setSettings: async ({ id, settings }) => {
91745
- const row = await this.deps.handle.getResolved(id);
91746
- if (row === null) return;
91747
- const parsed = SmtpInboundSettingsSchema.partial().parse(settings);
91748
- const next = MailboxBodySchema.parse({
91749
- ...row.data,
91750
- ...Object.fromEntries(Object.entries(parsed).filter(([, v]) => v !== void 0 && v !== ""))
91751
- });
91752
- await this.deps.handle.put({
91753
- id,
91754
- data: next
91755
- });
91756
- await this.reconcile(id);
91757
- },
91758
91968
  getBrokerConfig: async ({ id }) => {
91759
91969
  let row;
91760
91970
  try {
@@ -91776,19 +91986,6 @@ var SmtpInboundBroker = class {
91776
91986
  starttls: row.data.starttls
91777
91987
  };
91778
91988
  },
91779
- getSettingsSchema: async ({ kind }) => kind === "smtp-inbound" ? mailboxSettingsSchema() : null,
91780
- testSettings: async ({ kind, settings }) => {
91781
- if (kind !== "smtp-inbound") return {
91782
- ok: false,
91783
- error: `unsupported kind: ${kind}`
91784
- };
91785
- const parsed = SmtpInboundSettingsSchema.safeParse(settings);
91786
- if (!parsed.success) return {
91787
- ok: false,
91788
- error: parsed.error.message
91789
- };
91790
- return probeBind(parsed.data.port, parsed.data.bindHost);
91791
- },
91792
91989
  publish: async () => {
91793
91990
  throw new Error("smtp-inbound: a mailbox only receives — publish is not supported");
91794
91991
  },
@@ -91816,23 +92013,6 @@ var SmtpInboundBroker = class {
91816
92013
  };
91817
92014
  }
91818
92015
  };
91819
- /** A bind probe: can this port be taken on this host right now? */
91820
- function probeBind(port, host) {
91821
- const started = Date.now();
91822
- return new Promise((resolve) => {
91823
- const probe = (0, node_net.createServer)();
91824
- probe.once("error", (err) => resolve({
91825
- ok: false,
91826
- error: err.message
91827
- }));
91828
- probe.listen(port, host, () => {
91829
- probe.close(() => resolve({
91830
- ok: true,
91831
- latencyMs: Date.now() - started
91832
- }));
91833
- });
91834
- });
91835
- }
91836
92016
  function mailboxSettingsSchema() {
91837
92017
  return { sections: [{
91838
92018
  id: "mailbox",
@@ -136122,6 +136302,145 @@ var SmtpServerListener = class {
136122
136302
  }
136123
136303
  };
136124
136304
  //#endregion
136305
+ //#region src/bind-probe.ts
136306
+ /** A bind probe: can this port be taken on this host right now? */
136307
+ function probeBind(port, host) {
136308
+ const started = Date.now();
136309
+ return new Promise((resolve) => {
136310
+ const probe = (0, node_net.createServer)();
136311
+ probe.once("error", (err) => resolve({
136312
+ ok: false,
136313
+ error: err.message
136314
+ }));
136315
+ probe.listen(port, host, () => {
136316
+ probe.close(() => resolve({
136317
+ ok: true,
136318
+ latencyMs: Date.now() - started
136319
+ }));
136320
+ });
136321
+ });
136322
+ }
136323
+ //#endregion
136324
+ //#region src/mailbox-record-kinds.ts
136325
+ /**
136326
+ * The `smtp-inbound` mailbox as a record (D999): one `mailboxes` row per mailbox, owned by
136327
+ * `smtp-nodemailer`. The row id is the broker id. The SMTP AUTH password is a keychain-bound secret
136328
+ * field; nothing else holds a copy.
136329
+ */
136330
+ var MailboxBodySchema = entryBody({
136331
+ port: number().int().min(1).max(65535),
136332
+ bindHost: string().min(1),
136333
+ domain: string().min(1),
136334
+ requireAuth: boolean(),
136335
+ username: string(),
136336
+ password: string().optional().meta({ secret: true }),
136337
+ starttls: boolean(),
136338
+ maxMessageBytes: number().int().positive()
136339
+ });
136340
+ var mailboxesKind = defineEntryKind("mailboxes", {
136341
+ title: "Inbound mailboxes",
136342
+ nameField: "name",
136343
+ schema: MailboxBodySchema,
136344
+ writeTrigger: "an operator (or a consumer addon, once) adds or edits an inbound mailbox"
136345
+ });
136346
+ //#endregion
136347
+ //#region src/mailbox-instances.ts
136348
+ /**
136349
+ * The inbound mailboxes as `integration-instances` (D1013): one instance per `mailboxes` record,
136350
+ * over the SAME records and ids the `smtp-inbound` broker serves; the `mailboxes` kind of the
136351
+ * composed provider (the relays are the `relays` kind). A change re-applies the listener; removing
136352
+ * a mailbox a subscriber (camera email push) still reads is refused.
136353
+ */
136354
+ var MAILBOX_INSTANCE_KIND = "mailboxes";
136355
+ function statusOf(runtime) {
136356
+ if (runtime === null) return {
136357
+ state: "unknown",
136358
+ label: "Not listening"
136359
+ };
136360
+ if (runtime.status === "connected") return {
136361
+ state: "ok",
136362
+ label: "Listening"
136363
+ };
136364
+ return {
136365
+ state: "error",
136366
+ label: runtime.status,
136367
+ ...runtime.error !== null ? { detail: runtime.error } : {}
136368
+ };
136369
+ }
136370
+ function newMailboxBody(name) {
136371
+ const defaults = SmtpInboundSettingsSchema.parse({});
136372
+ return MailboxBodySchema.parse({
136373
+ name,
136374
+ port: defaults.port,
136375
+ bindHost: defaults.bindHost,
136376
+ domain: defaults.domain,
136377
+ requireAuth: defaults.requireAuth,
136378
+ username: `camstack-${(0, node_crypto.randomBytes)(4).toString("hex")}`,
136379
+ password: (0, node_crypto.randomBytes)(18).toString("base64url"),
136380
+ starttls: defaults.starttls,
136381
+ maxMessageBytes: defaults.maxMessageBytes
136382
+ });
136383
+ }
136384
+ function buildMailboxInstances(records, deps) {
136385
+ const users = deps.inbound.subscriberUsers();
136386
+ const base = new RecordIntegrationInstances(records, mailboxesKind, {
136387
+ description: {
136388
+ role: "services",
136389
+ instanceMode: "multiple",
136390
+ kind: "mailbox",
136391
+ canTest: true
136392
+ },
136393
+ formSchema: () => mailboxSettingsSchema(),
136394
+ initialBody: (name) => newMailboxBody(name),
136395
+ mintId: () => `smtp-inbound-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
136396
+ configured: () => true,
136397
+ health: (_body, id) => {
136398
+ const runtime = deps.inbound.runtimeOf(id);
136399
+ return {
136400
+ status: statusOf(runtime),
136401
+ ...runtime !== null ? { lastCheckedAt: runtime.checkedAt } : {}
136402
+ };
136403
+ },
136404
+ onChanged: (id) => deps.inbound.reconcileMailbox(id),
136405
+ test: async ({ id, values }) => {
136406
+ if (id === null) {
136407
+ const parsed = SmtpInboundSettingsSchema.safeParse(values);
136408
+ if (!parsed.success) return {
136409
+ success: false,
136410
+ status: "rejected",
136411
+ error: parsed.error.message
136412
+ };
136413
+ const bound = await probeBind(parsed.data.port, parsed.data.bindHost);
136414
+ return bound.ok ? {
136415
+ success: true,
136416
+ status: "validated",
136417
+ latencyMs: bound.latencyMs
136418
+ } : {
136419
+ success: false,
136420
+ status: "rejected",
136421
+ error: bound.error
136422
+ };
136423
+ }
136424
+ const runtime = deps.inbound.runtimeOf(id);
136425
+ return runtime?.status === "connected" ? {
136426
+ success: true,
136427
+ status: "validated"
136428
+ } : {
136429
+ success: false,
136430
+ status: "rejected",
136431
+ error: runtime?.error ?? "The mailbox is not listening"
136432
+ };
136433
+ }
136434
+ }).toProvider();
136435
+ return {
136436
+ ...base,
136437
+ deleteInstance: async (input) => {
136438
+ await assertInstanceUnused(input.id, [users]);
136439
+ return base.deleteInstance(input);
136440
+ }
136441
+ };
136442
+ }
136443
+ //#endregion
136125
136444
  //#region ../../node_modules/nodemailer/lib/mime-funcs/mime-types.js
136126
136445
  var require_mime_types = /* @__PURE__ */ __commonJSMin(((exports, module) => {
136127
136446
  var path$1 = require("path");
@@ -145531,7 +145850,7 @@ function buildTransportOptions(body) {
145531
145850
  }
145532
145851
  /** An absent `enabled` means on (D996). */
145533
145852
  function isOn(body) {
145534
- return body.enabled !== false;
145853
+ return isInstanceEnabled(body);
145535
145854
  }
145536
145855
  function coerceAddress(entry) {
145537
145856
  return typeof entry === "string" ? entry : entry.address;
@@ -145855,7 +146174,29 @@ var SmtpNodemailerAddon = class extends BaseAddon {
145855
146174
  },
145856
146175
  {
145857
146176
  capability: integrationInstancesCapability,
145858
- provider: this.instances.toProvider()
146177
+ provider: composeInstanceKinds([{
146178
+ kind: {
146179
+ id: "relays",
146180
+ label: "SMTP relay",
146181
+ functionCap: "smtp-provider",
146182
+ role: "services"
146183
+ },
146184
+ provider: this.instances.toProvider()
146185
+ }, {
146186
+ kind: {
146187
+ id: MAILBOX_INSTANCE_KIND,
146188
+ label: "Inbound mailbox (SMTP)",
146189
+ functionCap: "broker",
146190
+ brokerKind: SMTP_INBOUND_KIND,
146191
+ role: "services"
146192
+ },
146193
+ provider: buildMailboxInstances(records, { inbound })
146194
+ }], {
146195
+ role: "services",
146196
+ instanceMode: "multiple",
146197
+ kind: "relays",
146198
+ canTest: true
146199
+ })
145859
146200
  },
145860
146201
  {
145861
146202
  capability: brokerCapability,