@camstack/addon-export-hap 1.2.190 → 1.2.192

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.
@@ -4608,6 +4608,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4608
4608
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4609
4609
  json.type = "boolean";
4610
4610
  };
4611
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4612
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4613
+ };
4614
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4615
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4616
+ };
4611
4617
  var nullProcessor = (_schema, ctx, json, _params) => {
4612
4618
  if (ctx.target === "openapi-3.0") {
4613
4619
  json.type = "string";
@@ -4615,12 +4621,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4615
4621
  json.enum = [null];
4616
4622
  } else json.type = "null";
4617
4623
  };
4624
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4625
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4626
+ };
4618
4627
  var voidProcessor = (_schema, ctx, _json, _params) => {
4619
4628
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4620
4629
  };
4621
4630
  var neverProcessor = (_schema, _ctx, json, _params) => {
4622
4631
  json.not = {};
4623
4632
  };
4633
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4634
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4624
4635
  var dateProcessor = (_schema, ctx, _json, _params) => {
4625
4636
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4626
4637
  };
@@ -4652,12 +4663,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4652
4663
  json.enum = vals;
4653
4664
  }
4654
4665
  };
4666
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4667
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4668
+ };
4669
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4670
+ const _json = json;
4671
+ const pattern = schema._zod.pattern;
4672
+ if (!pattern) throw new Error("Pattern not found in template literal");
4673
+ _json.type = "string";
4674
+ _json.pattern = pattern.source;
4675
+ };
4676
+ var fileProcessor = (schema, _ctx, json, _params) => {
4677
+ const _json = json;
4678
+ const file = {
4679
+ type: "string",
4680
+ format: "binary",
4681
+ contentEncoding: "binary"
4682
+ };
4683
+ const { minimum, maximum, mime } = schema._zod.bag;
4684
+ if (minimum !== void 0) file.minLength = minimum;
4685
+ if (maximum !== void 0) file.maxLength = maximum;
4686
+ if (mime) if (mime.length === 1) {
4687
+ file.contentMediaType = mime[0];
4688
+ Object.assign(_json, file);
4689
+ } else {
4690
+ Object.assign(_json, file);
4691
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4692
+ }
4693
+ else Object.assign(_json, file);
4694
+ };
4695
+ var successProcessor = (_schema, _ctx, json, _params) => {
4696
+ json.type = "boolean";
4697
+ };
4655
4698
  var customProcessor = (_schema, ctx, _json, _params) => {
4656
4699
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4657
4700
  };
4701
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4702
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4703
+ };
4658
4704
  var transformProcessor = (_schema, ctx, _json, _params) => {
4659
4705
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4660
4706
  };
4707
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4708
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4709
+ };
4710
+ var setProcessor = (_schema, ctx, _json, _params) => {
4711
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4712
+ };
4661
4713
  var arrayProcessor = (schema, ctx, _json, params) => {
4662
4714
  const json = _json;
4663
4715
  const def = schema._zod.def;
@@ -4862,6 +4914,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4862
4914
  seen.ref = def.innerType;
4863
4915
  json.readOnly = true;
4864
4916
  };
4917
+ var promiseProcessor = (schema, ctx, _json, params) => {
4918
+ const def = schema._zod.def;
4919
+ process$1(def.innerType, ctx, params);
4920
+ const seen = ctx.seen.get(schema);
4921
+ seen.ref = def.innerType;
4922
+ };
4865
4923
  var optionalProcessor = (schema, ctx, _json, params) => {
4866
4924
  const def = schema._zod.def;
4867
4925
  process$1(def.innerType, ctx, params);
@@ -4874,6 +4932,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4874
4932
  const seen = ctx.seen.get(schema);
4875
4933
  seen.ref = innerType;
4876
4934
  };
4935
+ var allProcessors = {
4936
+ string: stringProcessor,
4937
+ number: numberProcessor,
4938
+ boolean: booleanProcessor,
4939
+ bigint: bigintProcessor,
4940
+ symbol: symbolProcessor,
4941
+ null: nullProcessor,
4942
+ undefined: undefinedProcessor,
4943
+ void: voidProcessor,
4944
+ never: neverProcessor,
4945
+ any: anyProcessor,
4946
+ unknown: unknownProcessor,
4947
+ date: dateProcessor,
4948
+ enum: enumProcessor,
4949
+ literal: literalProcessor,
4950
+ nan: nanProcessor,
4951
+ template_literal: templateLiteralProcessor,
4952
+ file: fileProcessor,
4953
+ success: successProcessor,
4954
+ custom: customProcessor,
4955
+ function: functionProcessor,
4956
+ transform: transformProcessor,
4957
+ map: mapProcessor,
4958
+ set: setProcessor,
4959
+ array: arrayProcessor,
4960
+ object: objectProcessor,
4961
+ union: unionProcessor,
4962
+ intersection: intersectionProcessor,
4963
+ tuple: tupleProcessor,
4964
+ record: recordProcessor,
4965
+ nullable: nullableProcessor,
4966
+ nonoptional: nonoptionalProcessor,
4967
+ default: defaultProcessor,
4968
+ prefault: prefaultProcessor,
4969
+ catch: catchProcessor,
4970
+ pipe: pipeProcessor,
4971
+ readonly: readonlyProcessor,
4972
+ promise: promiseProcessor,
4973
+ optional: optionalProcessor,
4974
+ lazy: lazyProcessor
4975
+ };
4976
+ function toJSONSchema(input, params) {
4977
+ if ("_idmap" in input) {
4978
+ const registry = input;
4979
+ const ctx = initializeContext({
4980
+ ...params,
4981
+ processors: allProcessors
4982
+ });
4983
+ const defs = {};
4984
+ for (const entry of registry._idmap.entries()) {
4985
+ const [_, schema] = entry;
4986
+ process$1(schema, ctx);
4987
+ }
4988
+ const schemas = {};
4989
+ ctx.external = {
4990
+ registry,
4991
+ uri: params?.uri,
4992
+ defs
4993
+ };
4994
+ for (const entry of registry._idmap.entries()) {
4995
+ const [key, schema] = entry;
4996
+ extractDefs(ctx, schema);
4997
+ schemas[key] = finalize(ctx, schema);
4998
+ }
4999
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
5000
+ return { schemas };
5001
+ }
5002
+ const ctx = initializeContext({
5003
+ ...params,
5004
+ processors: allProcessors
5005
+ });
5006
+ process$1(input, ctx);
5007
+ extractDefs(ctx, input);
5008
+ return finalize(ctx, input);
5009
+ }
4877
5010
  //#endregion
4878
5011
  //#region ../../node_modules/zod/v4/classic/iso.js
4879
5012
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5898,7 +6031,7 @@ var ZodIssueCode = {
5898
6031
  var ZodFirstPartyTypeKind;
5899
6032
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5900
6033
  //#endregion
5901
- //#region ../types/dist/sleep-BKClVk0K.mjs
6034
+ //#region ../types/dist/sleep-BaWhXZFm.mjs
5902
6035
  /**
5903
6036
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5904
6037
  * window to float samples (D455).
@@ -6046,9 +6179,16 @@ function isSecretMarker(value) {
6046
6179
  const ref = value["$secret"];
6047
6180
  return typeof ref === "string" && ref.length > 0;
6048
6181
  }
6182
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6183
+ function isSecretMarkerLike(value) {
6184
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6185
+ }
6049
6186
  function isSecretClear(value) {
6050
6187
  return isRecord$7(value) && value["$secretClear"] === true;
6051
6188
  }
6189
+ function isSecretFieldView(value) {
6190
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6191
+ }
6052
6192
  /**
6053
6193
  * The UI view of a stored secret field value: a marker becomes "set", inline
6054
6194
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6698,11 +6838,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6698
6838
  }
6699
6839
  return out;
6700
6840
  }
6841
+ /**
6842
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6843
+ *
6844
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6845
+ * scope (global, one node, one device, one integration, one row of a business
6846
+ * collection) and the field path inside that scope — so saving the same field
6847
+ * twice updates the same ref, and the ref itself says which settings blob
6848
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6849
+ * copied onto another ref does not decrypt.
6850
+ *
6851
+ * Array items are addressed by ITEM ID, never by index
6852
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6853
+ *
6854
+ * Pure and browser-safe: no node builtins, no I/O.
6855
+ */
6856
+ /** The URI scheme of every keychain ref. */
6857
+ var SECRET_REF_SCHEME = "secret://";
6701
6858
  var GLOBAL_SCOPE = { kind: "global" };
6702
6859
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6703
6860
  function globalSecretScope() {
6704
6861
  return GLOBAL_SCOPE;
6705
6862
  }
6863
+ /**
6864
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6865
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6866
+ * addon running forked.
6867
+ */
6868
+ function normalizeSecretOwner(addonId) {
6869
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6870
+ }
6706
6871
  function encodeSegment(value) {
6707
6872
  return encodeURIComponent(value);
6708
6873
  }
@@ -6713,6 +6878,16 @@ function decodeSegment(value) {
6713
6878
  return null;
6714
6879
  }
6715
6880
  }
6881
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6882
+ function formatSecretScope(scope) {
6883
+ switch (scope.kind) {
6884
+ case "global": return "global";
6885
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6886
+ case "device": return `device/${scope.deviceId}`;
6887
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6888
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6889
+ }
6890
+ }
6716
6891
  /**
6717
6892
  * The field path of a value inside an array item, addressed by the item's id:
6718
6893
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6721,6 +6896,13 @@ function decodeSegment(value) {
6721
6896
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6722
6897
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6723
6898
  }
6899
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6900
+ function buildSecretRef(parts) {
6901
+ const owner = normalizeSecretOwner(parts.owner);
6902
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6903
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6904
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6905
+ }
6724
6906
  function parseScope(segments) {
6725
6907
  switch (segments[0]) {
6726
6908
  case "global": return {
@@ -6861,7 +7043,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6861
7043
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6862
7044
  return out;
6863
7045
  }
6864
- function rowId(row, idKey) {
7046
+ function rowId$1(row, idKey) {
6865
7047
  const raw = row[idKey];
6866
7048
  if (typeof raw === "string" && raw.length > 0) return raw;
6867
7049
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6878,7 +7060,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6878
7060
  }
6879
7061
  const storedById = /* @__PURE__ */ new Map();
6880
7062
  for (const row of storedRows) {
6881
- const id = rowId(row, node.idKey);
7063
+ const id = rowId$1(row, node.idKey);
6882
7064
  if (id !== null) storedById.set(id, row);
6883
7065
  }
6884
7066
  const kept = /* @__PURE__ */ new Set();
@@ -6888,13 +7070,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6888
7070
  rows.push(row);
6889
7071
  continue;
6890
7072
  }
6891
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7073
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6892
7074
  kept.add(id);
6893
7075
  const withId = {
6894
7076
  ...row,
6895
7077
  [node.idKey]: row[node.idKey] ?? id
6896
7078
  };
6897
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7079
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6898
7080
  const storedRow = storedById.get(id) ?? {};
6899
7081
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6900
7082
  }
@@ -7986,6 +8168,10 @@ var BaseAddon = class {
7986
8168
  const stored = keychain ? await this.readAddonStoreWithRetry() : {};
7987
8169
  const patch = {};
7988
8170
  for (const key of keys) {
8171
+ if (tree.get(key)?.kind === "array") {
8172
+ patch[key] = [];
8173
+ continue;
8174
+ }
7989
8175
  const keychainStored = tree.has(key) || collectSecretMarkerRefs(stored[key]).length > 0;
7990
8176
  patch[key] = keychain && keychainStored ? SECRET_CLEAR : "";
7991
8177
  }
@@ -8625,6 +8811,45 @@ function normalizeAddonInitResult(result) {
8625
8811
  if (Array.isArray(result)) return { providers: result };
8626
8812
  return result;
8627
8813
  }
8814
+ var PREFIX = "records/";
8815
+ /** The base of every records failure. `detail` is the human part of the message. */
8816
+ var RecordsError = class extends Error {
8817
+ code;
8818
+ detail;
8819
+ constructor(code, detail) {
8820
+ super(`${PREFIX}${code}: ${detail}`);
8821
+ this.name = "RecordsError";
8822
+ this.code = code;
8823
+ this.detail = detail;
8824
+ }
8825
+ };
8826
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8827
+ var RevConflictError = class extends RecordsError {
8828
+ constructor(detail) {
8829
+ super("rev-conflict", detail);
8830
+ this.name = "RevConflictError";
8831
+ }
8832
+ };
8833
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8834
+ var RecordSecretUnavailableError = class extends RecordsError {
8835
+ constructor(detail) {
8836
+ super("secret-unavailable", detail);
8837
+ this.name = "RecordSecretUnavailableError";
8838
+ }
8839
+ };
8840
+ var InvalidRecordError = class extends RecordsError {
8841
+ constructor(detail) {
8842
+ super("invalid-record", detail);
8843
+ this.name = "InvalidRecordError";
8844
+ }
8845
+ };
8846
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8847
+ var DeclarationRefusedError = class extends RecordsError {
8848
+ constructor(detail) {
8849
+ super("declaration-refused", detail);
8850
+ this.name = "DeclarationRefusedError";
8851
+ }
8852
+ };
8628
8853
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8629
8854
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8630
8855
  var RECORD_DATABASES = ["settings", "events"];
@@ -8640,6 +8865,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8640
8865
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8641
8866
  var RECORD_BATCH_MAX = 1e3;
8642
8867
  var RECORD_QUERY_MAX = 1e3;
8868
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8869
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8870
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8871
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8872
+ /**
8873
+ * Secret fields of a record, addressed the way a Zod schema declares them
8874
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8875
+ * (`auth.accessToken`, `headers[].value`).
8876
+ *
8877
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8878
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8879
+ * key releases exactly that key's secret.
8880
+ *
8881
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8882
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8883
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8884
+ * leaf names its element: `headers[X-Api].value`.
8885
+ *
8886
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8887
+ */
8888
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8889
+ function parseSecretPath(path) {
8890
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8891
+ return path.split(".").map((raw) => {
8892
+ const each = raw.endsWith("[]");
8893
+ const map = raw.endsWith("{}");
8894
+ const key = each || map ? raw.slice(0, -2) : raw;
8895
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8896
+ return {
8897
+ key,
8898
+ each,
8899
+ map
8900
+ };
8901
+ });
8902
+ }
8903
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8904
+ function secretArrayPrefixes(path) {
8905
+ const segments = parseSecretPath(path);
8906
+ const prefixes = [];
8907
+ const walked = [];
8908
+ for (const segment of segments) {
8909
+ walked.push(segment.key);
8910
+ if (segment.each) prefixes.push(walked.join("."));
8911
+ }
8912
+ return prefixes;
8913
+ }
8914
+ function isRecord$4(value) {
8915
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8916
+ }
8917
+ function elementId(element, idKey, declared, prefix) {
8918
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8919
+ 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`);
8920
+ return id;
8921
+ }
8922
+ /**
8923
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8924
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8925
+ * result is a new body, `data` is untouched.
8926
+ */
8927
+ var REMOVE_LEAF = Symbol("remove-leaf");
8928
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8929
+ if (!isRecord$4(node)) return node;
8930
+ const segment = segments[index];
8931
+ if (segment === void 0) return node;
8932
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8933
+ const child = node[segment.key];
8934
+ const keys = [...walkedKeys, segment.key];
8935
+ const last = index === segments.length - 1;
8936
+ if (segment.each) {
8937
+ if (!Array.isArray(child)) return node;
8938
+ const prefix = keys.join(".");
8939
+ const idKey = arrayKeys[prefix];
8940
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8941
+ const mapped = child.map((element) => {
8942
+ const id = elementId(element, idKey, declared, prefix);
8943
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8944
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8945
+ });
8946
+ return {
8947
+ ...node,
8948
+ [segment.key]: mapped
8949
+ };
8950
+ }
8951
+ if (segment.map) {
8952
+ if (!isRecord$4(child)) return node;
8953
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8954
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8955
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8956
+ return [mapKey, visit({
8957
+ declared,
8958
+ concrete,
8959
+ value
8960
+ })];
8961
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8962
+ return {
8963
+ ...node,
8964
+ [segment.key]: Object.fromEntries(kept)
8965
+ };
8966
+ }
8967
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8968
+ if (last) {
8969
+ const replacement = visit({
8970
+ declared,
8971
+ concrete,
8972
+ value: child
8973
+ });
8974
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8975
+ return {
8976
+ ...node,
8977
+ [segment.key]: replacement
8978
+ };
8979
+ }
8980
+ return {
8981
+ ...node,
8982
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8983
+ };
8984
+ }
8985
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8986
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8987
+ let current = data;
8988
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8989
+ return current;
8990
+ }
8991
+ /**
8992
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8993
+ * record's refs never collide with the refs a legacy collection of the same name
8994
+ * already holds during an adoption.
8995
+ */
8996
+ function recordSecretCollection(kind) {
8997
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8998
+ }
8999
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9000
+ function recordSecretRef(owner, kind, rowId, concretePath) {
9001
+ return buildSecretRef({
9002
+ owner,
9003
+ scope: {
9004
+ kind: "row",
9005
+ collection: recordSecretCollection(kind),
9006
+ rowId
9007
+ },
9008
+ fieldPath: concretePath
9009
+ });
9010
+ }
9011
+ /**
9012
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9013
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9014
+ * token. The form hands it to the secret field, which reveals the value by ref
9015
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9016
+ * stored secret (the records door reads a view as KEEP).
9017
+ *
9018
+ * ONE implementation for the entries service and for every addon that serves
9019
+ * its own instances (`RecordIntegrationInstances`).
9020
+ */
9021
+ function isRecord$3(value) {
9022
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9023
+ }
9024
+ function secretViewsOf(owner, kind, id, decl, data) {
9025
+ if (decl.secretPaths.length === 0) return data;
9026
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9027
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9028
+ return {
9029
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9030
+ v: 1,
9031
+ set: true
9032
+ };
9033
+ });
9034
+ return isRecord$3(shown) ? shown : data;
9035
+ }
8643
9036
  /**
8644
9037
  * The share-view scope kinds a share-link token can carry. The hub mints
8645
9038
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8664,6 +9057,75 @@ var PeerBytesTicketSchema = object({
8664
9057
  */
8665
9058
  declaredBytes: number().int().nonnegative().nullable()
8666
9059
  });
9060
+ function defOf(schema) {
9061
+ const zodBag = Reflect.get(schema, "_zod");
9062
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9063
+ const def = Reflect.get(zodBag, "def");
9064
+ if (typeof def !== "object" || def === null) return {};
9065
+ return def;
9066
+ }
9067
+ function declaredHere(schema) {
9068
+ return globalRegistry.get(schema)?.secret === true;
9069
+ }
9070
+ /** Wrapper kinds whose `innerType` is the field itself. */
9071
+ var WRAPPERS = new Set([
9072
+ "optional",
9073
+ "nullable",
9074
+ "default",
9075
+ "prefault",
9076
+ "catch",
9077
+ "readonly",
9078
+ "nonoptional"
9079
+ ]);
9080
+ /**
9081
+ * The schema layers that make up ONE field: the schema itself and every
9082
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9083
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9084
+ * `.transform` on `in`).
9085
+ */
9086
+ function layersOf(schema) {
9087
+ const out = [];
9088
+ const queue = [schema];
9089
+ while (queue.length > 0) {
9090
+ const s = queue.shift();
9091
+ if (!s || out.includes(s)) continue;
9092
+ out.push(s);
9093
+ const def = defOf(s);
9094
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9095
+ if (def.type === "pipe") {
9096
+ if (def.in) queue.push(def.in);
9097
+ if (def.out) queue.push(def.out);
9098
+ }
9099
+ }
9100
+ return out;
9101
+ }
9102
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9103
+ function isZodSecret(schema) {
9104
+ return layersOf(schema).some(declaredHere);
9105
+ }
9106
+ /**
9107
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9108
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9109
+ * map" (`applianceSecrets{}`). A declared
9110
+ * object or array is reported as one path and not descended into — everything
9111
+ * under it is secret.
9112
+ */
9113
+ function collectZodSecretPaths(schema, prefix = "") {
9114
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9115
+ const paths = [];
9116
+ for (const layer of layersOf(schema)) {
9117
+ const def = defOf(layer);
9118
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9119
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9120
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9121
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9122
+ else if (def.type === "intersection") {
9123
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9124
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9125
+ }
9126
+ }
9127
+ return [...new Set(paths)];
9128
+ }
8667
9129
  /**
8668
9130
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8669
9131
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8730,6 +9192,111 @@ var RecordKindDeclarationSchema = object({
8730
9192
  }).strict();
8731
9193
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8732
9194
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9195
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9196
+ function assertValidDeclaration(name, decl) {
9197
+ const refuse = (why) => {
9198
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9199
+ };
9200
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9201
+ const seen = /* @__PURE__ */ new Set();
9202
+ for (const index of decl.indexes) {
9203
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9204
+ seen.add(index.name);
9205
+ }
9206
+ const { retention } = decl;
9207
+ const hasSecrets = decl.secretPaths.length > 0;
9208
+ if ("ttlMs" in retention) {
9209
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9210
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9211
+ }
9212
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9213
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9214
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9215
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9216
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9217
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9218
+ }
9219
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9220
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9221
+ }
9222
+ function bodyFieldsOf(schema) {
9223
+ return { ...toJSONSchema(schema, {
9224
+ unrepresentable: "any",
9225
+ io: "input"
9226
+ }) };
9227
+ }
9228
+ function isRecordLike(value) {
9229
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9230
+ }
9231
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9232
+ function hasNameField(json, field) {
9233
+ const branches = json["oneOf"] ?? json["anyOf"];
9234
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9235
+ const properties = json["properties"];
9236
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9237
+ }
9238
+ /**
9239
+ * Declare the kinds of a package. The keys are the kind names. The result is
9240
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9241
+ * types its handle from.
9242
+ */
9243
+ function defineRecordKinds(specs) {
9244
+ const out = {};
9245
+ for (const [name, spec] of Object.entries(specs)) {
9246
+ const secretPaths = collectZodSecretPaths(spec.schema);
9247
+ const nameField = spec.entry?.nameField ?? "name";
9248
+ const fields = bodyFieldsOf(spec.schema);
9249
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9250
+ const parsed = RecordKindDeclarationSchema.parse({
9251
+ database: spec.database,
9252
+ class: spec.class,
9253
+ writeTrigger: spec.writeTrigger,
9254
+ device: spec.device,
9255
+ at: spec.at,
9256
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9257
+ retention: spec.retention,
9258
+ deviceRemoval: spec.deviceRemoval,
9259
+ maxDataBytes: spec.maxDataBytes,
9260
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9261
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9262
+ transactFamily: spec.transactFamily,
9263
+ entry: spec.entry === void 0 ? void 0 : {
9264
+ title: spec.entry.title,
9265
+ nameField,
9266
+ fields
9267
+ }
9268
+ });
9269
+ assertValidDeclaration(name, parsed);
9270
+ out[name] = {
9271
+ name,
9272
+ schema: spec.schema,
9273
+ declaration: parsed
9274
+ };
9275
+ }
9276
+ return out;
9277
+ }
9278
+ /**
9279
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9280
+ * engine, never aged, belonging to no device.
9281
+ */
9282
+ function defineEntryKind(name, spec) {
9283
+ const defined = defineRecordKinds({ [name]: {
9284
+ schema: spec.schema,
9285
+ class: "config",
9286
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9287
+ retention: { none: "an entry goes only when the operator deletes it" },
9288
+ ...spec.database === void 0 ? {} : { database: spec.database },
9289
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9290
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9291
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9292
+ entry: {
9293
+ title: spec.title,
9294
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9295
+ }
9296
+ } })[name];
9297
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9298
+ return defined;
9299
+ }
8733
9300
  object({
8734
9301
  field: string().min(1),
8735
9302
  on: literal("advance")
@@ -11442,7 +12009,7 @@ object({
11442
12009
  params: record(string(), union([string(), number()])).optional()
11443
12010
  });
11444
12011
  //#endregion
11445
- //#region ../types/dist/composition-BodkvOV0.mjs
12012
+ //#region ../types/dist/composition-CRNwcFYY.mjs
11446
12013
  var AUDIO_ENCODER_BY_CODEC = {
11447
12014
  opus: "libopus",
11448
12015
  aac: "aac",
@@ -11619,6 +12186,7 @@ function buildVideoArgs(video, outputArgs, filterGraph, hwEncode) {
11619
12186
  if (video.level !== void 0) args.push("-level", video.level);
11620
12187
  if (video.pixelFormat !== void 0) args.push("-pix_fmt", video.pixelFormat);
11621
12188
  if (video.fps !== void 0) args.push("-r", String(video.fps));
12189
+ if (video.fpsMode !== void 0) args.push("-fps_mode", video.fpsMode);
11622
12190
  if (video.gopFrames !== void 0) args.push("-g", String(video.gopFrames));
11623
12191
  if (video.forceKeyFramesSeconds !== void 0) args.push("-force_key_frames", `expr:gte(t,n_forced*${video.forceKeyFramesSeconds})`);
11624
12192
  if (video.bf !== void 0) args.push("-bf", String(video.bf));
@@ -12800,38 +13368,6 @@ function validateExpressionSource(src) {
12800
13368
  return null;
12801
13369
  }
12802
13370
  /**
12803
- * One power reading becomes a washer, dryer or dishwasher (D944 helper).
12804
- *
12805
- * Standby of the control board is under 5 W; a motor or a heater is far
12806
- * above that, so 5 W is the line. A door lock or a short pump spike is not
12807
- * a cycle, so running starts only after 30 s above the line.
12808
- *
12809
- * A wash, dry or dishwasher pause (soak, heat-wait, heater off between
12810
- * bursts) lasts several minutes. Ending the cycle on the first dip would
12811
- * report "finished" in the middle of the program, so the stop dwell is
12812
- * 10 minutes on every type. The number is stored per type so one machine
12813
- * can move later without moving the others.
12814
- */
12815
- var APPLIANCE_TEMPLATE_ID = "appliance";
12816
- var APPLIANCE_KINDS = [
12817
- "washer",
12818
- "dryer",
12819
- "dishwasher"
12820
- ];
12821
- DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher;
12822
- /**
12823
- * A dumb plug-in stove or heater, built from a smart plug (a `Heater`).
12824
- *
12825
- * The plug is the actuator: `switch.setState` is a FORWARD to the plug's own
12826
- * (D967), so the heater switches exactly as the plug does. Running is the
12827
- * plug being on; when a power reading is also named, running is the draw
12828
- * staying above the line instead (a plug left on with the stove's own
12829
- * thermostat open is not heating). 50 W is far above any standby and below
12830
- * the smallest radiator.
12831
- */
12832
- var HEATER_TEMPLATE_ID = "heater";
12833
- DeviceType.Heater;
12834
- /**
12835
13371
  * Statistics and integrals over a history read (D944).
12836
13372
  *
12837
13373
  * Pure: the same points always give the same answer, so a restart recomputes
@@ -12975,34 +13511,6 @@ var HelperSpecSchema = discriminatedUnion("kind", [
12975
13511
  /** Actuator groups only. Readings leave this unset. */
12976
13512
  active: ActiveCriterionSchema.optional()
12977
13513
  }),
12978
- object({
12979
- kind: literal("appliance"),
12980
- templateId: literal(APPLIANCE_TEMPLATE_ID),
12981
- appliance: _enum(APPLIANCE_KINDS),
12982
- thresholdWatts: number().positive(),
12983
- startDwellMs: number().int().nonnegative(),
12984
- stopDwellMs: number().int().nonnegative(),
12985
- member: HelperMemberSchema,
12986
- /**
12987
- * The plug that powers the appliance (`switch.on`). Optional: when set, the
12988
- * composition carries a `power-source` feature, so the hub can cut and restore
12989
- * that plug (power-source link of a NEW-target composition).
12990
- */
12991
- powerSwitch: HelperMemberSchema.optional(),
12992
- /** How long a forced restart keeps the plug off; the cap's default when unset. */
12993
- offSeconds: number().optional()
12994
- }),
12995
- object({
12996
- kind: literal("heater"),
12997
- templateId: literal(HEATER_TEMPLATE_ID),
12998
- /** The plug, read and commanded at `switch.on`. */
12999
- plug: HelperMemberSchema,
13000
- /** The plug's power reading, when it has one: running is then the draw, not the switch. */
13001
- meter: HelperMemberSchema.optional(),
13002
- thresholdWatts: number().positive(),
13003
- startDwellMs: number().int().nonnegative(),
13004
- stopDwellMs: number().int().nonnegative()
13005
- }),
13006
13514
  object({
13007
13515
  kind: literal("statistic"),
13008
13516
  stat: _enum(STATISTIC_STATS),
@@ -13226,7 +13734,7 @@ var CompositionSchema = object({
13226
13734
  kind: literal("existing"),
13227
13735
  device: CompositionSourceRefSchema
13228
13736
  })]),
13229
- features: array(CompositionFeatureSchema).min(1).max(16),
13737
+ features: array(CompositionFeatureSchema).min(0).max(16),
13230
13738
  /**
13231
13739
  * Present when the block is a helper template. Absent on a free
13232
13740
  * composition (the room example, device 4603). The editor reads this,
@@ -13444,6 +13952,205 @@ var IntegrationInstanceRefSchema = object({
13444
13952
  ]),
13445
13953
  candidateStableId: string().optional()
13446
13954
  });
13955
+ /**
13956
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13957
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13958
+ *
13959
+ * Every instance is one record of the addon's own kind, keyed by the
13960
+ * `integrations` registry id. The records door does the secret work: a field the
13961
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13962
+ * deleting the row deletes the secret, and one row's value is never another's.
13963
+ *
13964
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13965
+ * token or the view the form was given KEEP the stored secret;
13966
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13967
+ */
13968
+ /** The most instances one addon lists (an integrations page, not a table). */
13969
+ var INSTANCES_LIST_MAX = 1e3;
13970
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13971
+ function topLevelSecretKeys(paths) {
13972
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13973
+ }
13974
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13975
+ function secretMapKeys(paths) {
13976
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13977
+ }
13978
+ /**
13979
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13980
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13981
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13982
+ */
13983
+ function secretMapPatch(value) {
13984
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13985
+ const out = {};
13986
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13987
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13988
+ return Object.keys(out).length > 0 ? out : null;
13989
+ }
13990
+ /** Does the kind's body schema carry an `enabled` field? */
13991
+ function declaresEnabled(kind) {
13992
+ const json = toJSONSchema(kind.schema, {
13993
+ unrepresentable: "any",
13994
+ io: "input"
13995
+ });
13996
+ const properties = Reflect.get(json, "properties");
13997
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13998
+ }
13999
+ var RecordIntegrationInstances = class {
14000
+ records;
14001
+ kind;
14002
+ hooks;
14003
+ handle;
14004
+ secretKeys;
14005
+ secretMaps;
14006
+ nameField;
14007
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
14008
+ registryOwnsEnabled;
14009
+ constructor(records, kind, hooks) {
14010
+ this.records = records;
14011
+ this.kind = kind;
14012
+ this.hooks = hooks;
14013
+ this.handle = records.kind(kind);
14014
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
14015
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
14016
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
14017
+ this.registryOwnsEnabled = hooks.description.role === "devices";
14018
+ 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"`);
14019
+ }
14020
+ /**
14021
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
14022
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
14023
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14024
+ */
14025
+ async readResolved(id) {
14026
+ try {
14027
+ const record = await this.handle.getResolved(id);
14028
+ return record === null ? null : {
14029
+ id,
14030
+ body: record.data,
14031
+ enabled: record.data.enabled !== false,
14032
+ secrets: "resolved"
14033
+ };
14034
+ } catch (err) {
14035
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
14036
+ const stored = await this.handle.get(id);
14037
+ if (stored === null) return null;
14038
+ return {
14039
+ id,
14040
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
14041
+ enabled: stored.data.enabled !== false,
14042
+ secrets: "unavailable"
14043
+ };
14044
+ }
14045
+ }
14046
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
14047
+ async getResolved(id) {
14048
+ return (await this.readResolved(id))?.body ?? null;
14049
+ }
14050
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
14051
+ async listResolved() {
14052
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
14053
+ const out = [];
14054
+ for (const record of page.records) {
14055
+ const read = await this.readResolved(record.id);
14056
+ if (read !== null) out.push(read);
14057
+ }
14058
+ return out;
14059
+ }
14060
+ viewOf(record) {
14061
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
14062
+ const rawName = record.data[this.nameField];
14063
+ const kind = this.hooks.kindOf?.(record.data);
14064
+ const health = this.hooks.health?.(record.data, record.id);
14065
+ return {
14066
+ id: record.id,
14067
+ name: typeof rawName === "string" ? rawName : record.id,
14068
+ configured: this.hooks.configured(record.data),
14069
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
14070
+ formValues: shown,
14071
+ ...kind !== void 0 ? { kind } : {},
14072
+ ...health?.status !== void 0 ? { status: health.status } : {},
14073
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
14074
+ };
14075
+ }
14076
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
14077
+ ...this.hooks.description,
14078
+ mintsId: true
14079
+ };
14080
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
14081
+ listInstances = async () => {
14082
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
14083
+ };
14084
+ getInstance = async ({ id }) => {
14085
+ const record = await this.handle.get(id);
14086
+ return record === null ? null : this.viewOf(record);
14087
+ };
14088
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
14089
+ createInstance = async ({ id, name, kind }) => {
14090
+ const minted = id ?? this.hooks.mintId?.({
14091
+ name,
14092
+ ...kind !== void 0 ? { kind } : {}
14093
+ });
14094
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
14095
+ await this.handle.put({
14096
+ id: minted,
14097
+ data: this.hooks.initialBody(name, kind)
14098
+ }, { ifRev: 0 });
14099
+ await this.hooks.onChanged?.(minted, "created");
14100
+ return { id: minted };
14101
+ };
14102
+ updateInstance = async ({ id, name, values }) => {
14103
+ const patch = {};
14104
+ for (const [key, value] of Object.entries(values)) {
14105
+ if (value === void 0) continue;
14106
+ if (this.secretMaps.has(key)) {
14107
+ const entries = secretMapPatch(value);
14108
+ if (entries !== null) patch[key] = entries;
14109
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
14110
+ else if (isSecretClear(value)) patch[key] = null;
14111
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
14112
+ }
14113
+ if (name !== void 0) patch[this.nameField] = name;
14114
+ await this.handle.patch(id, patch);
14115
+ await this.hooks.onChanged?.(id, "updated");
14116
+ return { ok: true };
14117
+ };
14118
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
14119
+ setInstanceEnabled = async ({ id, enabled }) => {
14120
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
14121
+ await this.handle.patch(id, { enabled });
14122
+ await this.hooks.onChanged?.(id, "enabled");
14123
+ return { ok: true };
14124
+ };
14125
+ /** The row and its keychain refs go together (the records door). */
14126
+ deleteInstance = async ({ id }) => {
14127
+ await this.handle.delete(id);
14128
+ await this.hooks.onChanged?.(id, "deleted");
14129
+ return { ok: true };
14130
+ };
14131
+ testInstance = async (input) => {
14132
+ if (this.hooks.test === void 0) return {
14133
+ success: false,
14134
+ status: "unsupported",
14135
+ error: "This integration declares no connection test"
14136
+ };
14137
+ return this.hooks.test(input);
14138
+ };
14139
+ /** The flat provider object to hand to `registerProvider`. */
14140
+ toProvider() {
14141
+ return {
14142
+ describe: this.describe,
14143
+ instanceFormSchema: this.instanceFormSchema,
14144
+ listInstances: this.listInstances,
14145
+ getInstance: this.getInstance,
14146
+ createInstance: this.createInstance,
14147
+ updateInstance: this.updateInstance,
14148
+ setInstanceEnabled: this.setInstanceEnabled,
14149
+ deleteInstance: this.deleteInstance,
14150
+ testInstance: this.testInstance
14151
+ };
14152
+ }
14153
+ };
13447
14154
  var EncodeProfileSchema = object({
13448
14155
  video: object({
13449
14156
  codec: _enum([
@@ -49146,49 +49853,6 @@ function actuator(input) {
49146
49853
  };
49147
49854
  }
49148
49855
  new Map(GROUP_TEMPLATES.map((template) => [template.id, template]));
49149
- var PowerSourceRefusalReasonSchema = _enum([
49150
- "no-power-source",
49151
- "switch-missing",
49152
- "switch-offline",
49153
- "switch-unknown",
49154
- "restart-in-progress",
49155
- "switch-call-failed"
49156
- ]);
49157
- var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
49158
- accepted: literal(false),
49159
- reason: PowerSourceRefusalReasonSchema,
49160
- /** One line for the operator, naming the switch. */
49161
- message: string()
49162
- })]);
49163
- var PowerSourceInfoSchema = object({
49164
- /** False when the device has no power source linked; the rest is then empty. */
49165
- linked: boolean(),
49166
- switchDeviceId: number().nullable(),
49167
- switchName: string().nullable(),
49168
- /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
49169
- switchOn: boolean().nullable(),
49170
- switchOnline: boolean().nullable(),
49171
- restartInProgress: boolean(),
49172
- offSeconds: number().int()
49173
- });
49174
- object({
49175
- /** Null while the switch has not reported: unknown is never `false` (D393). */
49176
- switchOn: boolean().nullable(),
49177
- offSeconds: number().int(),
49178
- lastFetchedAt: number()
49179
- });
49180
- DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
49181
- var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
49182
- systemMethod(deviceInput$2, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49183
- kind: "mutation",
49184
- auth: "admin"
49185
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49186
- kind: "mutation",
49187
- auth: "admin"
49188
- }), systemMethod(deviceInput$2, PowerSourceActionResultSchema, {
49189
- kind: "mutation",
49190
- auth: "admin"
49191
- });
49192
49856
  DeviceFeature.LightColorRgb, DeviceFeature.LightColorHsv, DeviceFeature.LightColorMired;
49193
49857
  DeviceType.Camera;
49194
49858
  `${COMPOSED_DEVICE_STABLE_ID_PREFIX}`;
@@ -49216,6 +49880,165 @@ var ComposableCapabilitiesSchema = object({ caps: array(object({
49216
49880
  }).optional()
49217
49881
  })) });
49218
49882
  /**
49883
+ * A saved Customize assignment (D936). The schema is the type: callers use
49884
+ * `z.infer`, they do not restate the shape.
49885
+ */
49886
+ var OverrideSourceSchema = object({
49887
+ addonId: string().min(1),
49888
+ stableId: string().min(1),
49889
+ cap: string().min(1),
49890
+ fieldPath: string().min(1)
49891
+ });
49892
+ var IdentityTransformDraftSchema = object({ kind: literal("identity") });
49893
+ var InvertTransformDraftSchema = object({ kind: literal("invert") });
49894
+ var ThresholdTransformDraftSchema = object({
49895
+ kind: literal("threshold"),
49896
+ comparison: _enum(["gte", "lte"]),
49897
+ threshold: number(),
49898
+ startDwellMs: number().nonnegative(),
49899
+ stopDwellMs: number().nonnegative()
49900
+ });
49901
+ var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
49902
+ IdentityTransformDraftSchema,
49903
+ InvertTransformDraftSchema,
49904
+ ThresholdTransformDraftSchema,
49905
+ object({
49906
+ kind: literal("linear"),
49907
+ scale: number(),
49908
+ offset: number(),
49909
+ clampMin: number().optional(),
49910
+ clampMax: number().optional()
49911
+ }),
49912
+ object({
49913
+ kind: literal("enum-map"),
49914
+ mapping: record(string(), string().nullable())
49915
+ }),
49916
+ object({ kind: literal("number") })
49917
+ ]);
49918
+ var ScalarOverrideDraftSchema = object({
49919
+ kind: literal("scalar"),
49920
+ cap: string().min(1),
49921
+ targetId: string().min(1),
49922
+ source: OverrideSourceSchema,
49923
+ transform: CustomizeTransformDraftSchema
49924
+ });
49925
+ var KeyedArrayOverrideDraftSchema = object({
49926
+ kind: literal("keyedArray"),
49927
+ cap: string().min(1),
49928
+ targetId: string().min(1),
49929
+ key: string().min(1),
49930
+ label: string().min(1),
49931
+ fieldPath: string().min(1),
49932
+ source: OverrideSourceSchema,
49933
+ transform: CustomizeTransformDraftSchema
49934
+ });
49935
+ var PulseOverrideDraftSchema = object({
49936
+ kind: literal("pulse"),
49937
+ cap: string().min(1),
49938
+ targetId: string().min(1),
49939
+ enabled: boolean(),
49940
+ debounceMs: number().nonnegative(),
49941
+ edges: array(_enum([
49942
+ "rising",
49943
+ "button",
49944
+ "native-event"
49945
+ ])).min(1).optional(),
49946
+ sources: array(OverrideSourceSchema).min(1)
49947
+ });
49948
+ var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
49949
+ "in-addition",
49950
+ "confirm",
49951
+ "replace"
49952
+ ]).optional() });
49953
+ discriminatedUnion("kind", [
49954
+ ScalarOverrideDraftSchema,
49955
+ KeyedArrayOverrideDraftSchema,
49956
+ PulseOverrideDraftSchema,
49957
+ object({
49958
+ kind: literal("span"),
49959
+ cap: string().min(1),
49960
+ targetId: string().min(1),
49961
+ timeoutMs: number().nonnegative(),
49962
+ cooldownMs: number().nonnegative().optional(),
49963
+ sources: array(SpanSourceDraftSchema)
49964
+ })
49965
+ ]);
49966
+ object({
49967
+ targetId: string().min(1),
49968
+ configured: boolean(),
49969
+ source: _enum(["native", "assigned"]),
49970
+ state: _enum([
49971
+ "active",
49972
+ "stale",
49973
+ "released",
49974
+ "unavailable"
49975
+ ]),
49976
+ reason: string().nullable()
49977
+ });
49978
+ /**
49979
+ * What a running-threshold proposal says (planning#405). The schema is the
49980
+ * type: the algorithm, the capability method and the UI all read `z.infer`.
49981
+ *
49982
+ * A proposal is read-only advice: it carries the numbers it was derived from
49983
+ * (`evidence`) so the operator can judge it, and an `insufficient` answer names
49984
+ * WHY with a typed reason and the catalog defaults, never an invented number.
49985
+ */
49986
+ var RunningProposalTierSchema = _enum(["raw", "5m"]);
49987
+ var RunningProposalConfidenceSchema = _enum([
49988
+ "high",
49989
+ "medium",
49990
+ "low"
49991
+ ]);
49992
+ var RunningProposalInsufficientReasonSchema = _enum([
49993
+ "no-history",
49994
+ "span-too-short",
49995
+ "truncated",
49996
+ "no-idle-floor",
49997
+ "no-runs",
49998
+ "no-separation"
49999
+ ]);
50000
+ var RunningProposalReplaySchema = object({
50001
+ /** Intervals the real dwell expression held true over the window. */
50002
+ intervals: number().int().nonnegative(),
50003
+ /** Intervals outside every run, or a second interval inside one. */
50004
+ extra: number().int().nonnegative(),
50005
+ /** Runs without an interval of their own (none, or merged into a neighbour). */
50006
+ missed: number().int().nonnegative()
50007
+ });
50008
+ var RunningProposalEvidenceSchema = object({
50009
+ tier: RunningProposalTierSchema,
50010
+ spanMs: number().nonnegative(),
50011
+ from: number(),
50012
+ to: number(),
50013
+ points: number().int().nonnegative(),
50014
+ runsFound: number().int().nonnegative(),
50015
+ pausesFound: number().int().nonnegative(),
50016
+ longestPauseMs: number().nonnegative(),
50017
+ idleFloorW: number(),
50018
+ noiseCeilingW: number(),
50019
+ plateauW: number(),
50020
+ replay: RunningProposalReplaySchema
50021
+ });
50022
+ var RunningProposalInsufficientEvidenceSchema = object({
50023
+ spanMs: number().nonnegative(),
50024
+ points: number().int().nonnegative(),
50025
+ runsFound: number().int().nonnegative()
50026
+ });
50027
+ var RunningThresholdProposalSchema = discriminatedUnion("state", [object({
50028
+ state: literal("proposal"),
50029
+ transform: ThresholdTransformDraftSchema,
50030
+ evidence: RunningProposalEvidenceSchema,
50031
+ confidence: RunningProposalConfidenceSchema,
50032
+ /** Why the confidence is not higher; empty when nothing held it back. */
50033
+ notes: array(string())
50034
+ }), object({
50035
+ state: literal("insufficient"),
50036
+ reason: RunningProposalInsufficientReasonSchema,
50037
+ evidence: RunningProposalInsufficientEvidenceSchema,
50038
+ /** The catalog defaults, offered as what stands when nothing better is known. */
50039
+ fallback: ThresholdTransformDraftSchema
50040
+ })]);
50041
+ /**
49219
50042
  * The report of a one-shot "move this owner's plaintext secrets into the
49220
50043
  * keychain" run (D878). COUNTS only - never a value, never a ref.
49221
50044
  *
@@ -49505,6 +50328,14 @@ method(object({}), object({ blocks: array(CoreBlockSchema) }), { auth: "admin" }
49505
50328
  kind: "mutation",
49506
50329
  auth: "admin",
49507
50330
  access: "view"
50331
+ }), method(object({
50332
+ deviceId: number().int(),
50333
+ cap: string().min(1),
50334
+ fieldPath: string().min(1),
50335
+ deviceType: _enum(DeviceType).optional()
50336
+ }), RunningThresholdProposalSchema, {
50337
+ auth: "admin",
50338
+ access: "view"
49508
50339
  }), method(object({
49509
50340
  blockId: string().min(1),
49510
50341
  trace: AutomationRunTraceSchema.optional(),
@@ -50369,7 +51200,53 @@ method(object({
50369
51200
  * exposes only the COMMON surface: link state, supported device
50370
51201
  * kinds (so the UI can filter the device picker), and per-device
50371
51202
  * expose/unexpose.
51203
+ *
51204
+ * INSTANCES. One export addon can serve several independent targets (a
51205
+ * HomeKit bridge, a Home Assistant broker). `listInstances` names them.
51206
+ * `instanceId` on a READ is optional: absent = the whole addon (linked if any
51207
+ * enabled instance is, `exposedDeviceCount` = distinct devices, `setup` = the
51208
+ * default instance's); present = that instance; an id the provider does not
51209
+ * serve is refused with `ExportInstanceUnknownError` (`export-instance-unknown`),
51210
+ * never answered empty. `instanceId` on a WRITE is REQUIRED: a membership
51211
+ * change always names the target it changes. A single-instance provider
51212
+ * accepts an absent id on a read or its own id, and refuses any other.
51213
+ */
51214
+ /** Which instance of an export addon a call addresses. Absent on a read = the whole addon. */
51215
+ var InstanceIdSchema$1 = string().min(1);
51216
+ var InstancePinSchema = object({ instanceId: InstanceIdSchema$1.optional() });
51217
+ /** One independent export target of an addon. */
51218
+ var ExportInstanceSchema = object({
51219
+ instanceId: InstanceIdSchema$1,
51220
+ name: string(),
51221
+ enabled: boolean(),
51222
+ kind: string().optional()
51223
+ });
51224
+ var EXPORT_INSTANCE_UNKNOWN = "export-instance-unknown";
51225
+ /** The named failure of an `instanceId` the provider does not serve. The message starts with the code. */
51226
+ var ExportInstanceUnknownError = class extends Error {
51227
+ code = EXPORT_INSTANCE_UNKNOWN;
51228
+ instanceId;
51229
+ constructor(addon, instanceId) {
51230
+ super(`${EXPORT_INSTANCE_UNKNOWN}: ${addon} serves no instance "${instanceId}"`);
51231
+ this.name = "ExportInstanceUnknownError";
51232
+ this.instanceId = instanceId;
51233
+ }
51234
+ };
51235
+ /**
51236
+ * The instance a `getStatus` call names. The cap's `status` block injects a per-device
51237
+ * `getStatus({ deviceId })` beside the method's own `{ instanceId? }`, so the provider sees
51238
+ * both shapes; only the second names an instance (a per-device status read is addon-wide).
50372
51239
  */
51240
+ function statusInstanceOf(input) {
51241
+ return "instanceId" in input ? input.instanceId : void 0;
51242
+ }
51243
+ /**
51244
+ * A single-instance provider's check: an absent id or its own passes, any other throws
51245
+ * `ExportInstanceUnknownError`.
51246
+ */
51247
+ function assertOwnExportInstance(addon, own, instanceId) {
51248
+ if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51249
+ }
50373
51250
  var LinkStateSchema = _enum([
50374
51251
  "unlinked",
50375
51252
  "linked",
@@ -50420,10 +51297,14 @@ var ExposedDeviceSchema = object({
50420
51297
  capabilities: array(string()).optional()
50421
51298
  });
50422
51299
  var ExposeInputSchema = object({
51300
+ instanceId: InstanceIdSchema$1,
50423
51301
  deviceId: string(),
50424
51302
  capabilities: array(string()).optional()
50425
51303
  });
50426
- var UnexposeInputSchema = object({ deviceId: string() });
51304
+ var UnexposeInputSchema = object({
51305
+ instanceId: InstanceIdSchema$1,
51306
+ deviceId: string()
51307
+ });
50427
51308
  /**
50428
51309
  * What an exporter may expose besides devices (D968). An action and a
50429
51310
  * notification target are LIST ENTRIES, never devices (D954): they enter an
@@ -50452,8 +51333,14 @@ var ExposedEntitySchema = object({
50452
51333
  entity: ExportEntityRefSchema,
50453
51334
  exposedAs: string().optional()
50454
51335
  });
50455
- var ExposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
50456
- var UnexposeEntityInputSchema = object({ entity: ExportEntityRefSchema });
51336
+ var ExposeEntityInputSchema = object({
51337
+ instanceId: InstanceIdSchema$1,
51338
+ entity: ExportEntityRefSchema
51339
+ });
51340
+ var UnexposeEntityInputSchema = object({
51341
+ instanceId: InstanceIdSchema$1,
51342
+ entity: ExportEntityRefSchema
51343
+ });
50457
51344
  var deviceExportCapability = {
50458
51345
  name: "device-export",
50459
51346
  scope: "system",
@@ -50473,9 +51360,10 @@ var deviceExportCapability = {
50473
51360
  */
50474
51361
  exposesDeviceSettings: true,
50475
51362
  methods: {
50476
- getStatus: method(_void(), DeviceExportStatusSchema),
50477
- listSupportedDeviceKinds: method(_void(), array(DeviceKindSchema)),
50478
- listExposedDevices: method(_void(), array(ExposedDeviceSchema)),
51363
+ getStatus: method(InstancePinSchema, DeviceExportStatusSchema),
51364
+ listInstances: method(_void(), array(ExportInstanceSchema)),
51365
+ listSupportedDeviceKinds: method(InstancePinSchema, array(DeviceKindSchema)),
51366
+ listExposedDevices: method(InstancePinSchema, array(ExposedDeviceSchema)),
50479
51367
  exposeDevice: method(ExposeInputSchema, _void(), {
50480
51368
  kind: "mutation",
50481
51369
  auth: "admin"
@@ -50485,7 +51373,7 @@ var deviceExportCapability = {
50485
51373
  auth: "admin"
50486
51374
  }),
50487
51375
  listSupportedEntityKinds: optionalMethod(_void(), array(ExportEntityKindSchema)),
50488
- listExposedEntities: optionalMethod(_void(), array(ExposedEntitySchema)),
51376
+ listExposedEntities: optionalMethod(InstancePinSchema, array(ExposedEntitySchema)),
50489
51377
  exposeEntity: optionalMethod(ExposeEntityInputSchema, _void(), {
50490
51378
  kind: "mutation",
50491
51379
  auth: "admin"
@@ -53690,15 +54578,15 @@ var FanPresetCaptureResultSchema = object({
53690
54578
  items: array(FanCaptureItemSchema),
53691
54579
  omitted: array(FanCaptureOmissionSchema)
53692
54580
  });
53693
- var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
54581
+ var deviceInput$2 = object({ deviceId: number().int().nonnegative() });
53694
54582
  DeviceType.Fan;
53695
- method(deviceInput$1, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$1.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
54583
+ method(deviceInput$2, array(FanPresetSchema), { auth: "protected" }), method(deviceInput$2.extend({ presets: array(FanPresetSchema).max(12) }), FanPresetsSetResultSchema, {
53696
54584
  kind: "mutation",
53697
54585
  auth: "admin"
53698
- }), method(deviceInput$1.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
54586
+ }), method(deviceInput$2.extend({ presetId: string().min(1) }), FanPresetApplyResultSchema, {
53699
54587
  kind: "mutation",
53700
54588
  auth: "protected"
53701
- }), method(deviceInput$1.extend({
54589
+ }), method(deviceInput$2.extend({
53702
54590
  fields: array(FanCaptureFieldSchema).optional(),
53703
54591
  steps: array(ActionStepSchema).max(20).default([])
53704
54592
  }), FanPresetCaptureResultSchema, { auth: "protected" });
@@ -54238,13 +55126,65 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54238
55126
  */
54239
55127
  var ConfigSchemaPassthrough$3 = custom();
54240
55128
  var IntegrationInstanceIdSchema = string().min(1);
55129
+ var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
55130
+ /**
55131
+ * One kind of instance a provider can create (an adapter, an account type). The sign-in and
55132
+ * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
55133
+ * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
55134
+ * interactive account link (popup) and may carry `{{brokerId}}`, which the UI replaces with the
55135
+ * instance id.
55136
+ */
55137
+ var IntegrationInstanceKindSchema = object({
55138
+ /** Stable id of the kind, sent back as `createInstance.kind`. */
55139
+ id: string().min(1),
55140
+ label: string().min(1),
55141
+ /** The kind signs in through a server-held interactive session. */
55142
+ signIn: object({
55143
+ basePath: string().min(1),
55144
+ methods: array(_enum(["device-code", "proxy"])).optional()
55145
+ }).optional(),
55146
+ /** Relative hub path to start an interactive account link of an instance of this kind. */
55147
+ connectPath: string().min(1).optional(),
55148
+ /** Relative hub path to disconnect that account. */
55149
+ disconnectPath: string().min(1).optional()
55150
+ });
54241
55151
  var IntegrationInstanceDescriptionSchema = object({
55152
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
55153
+ role: _enum([
55154
+ "devices",
55155
+ "services",
55156
+ "both"
55157
+ ]),
55158
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
55159
+ discovery: object({
55160
+ mode: _enum([
55161
+ "none",
55162
+ "lan",
55163
+ "account"
55164
+ ]),
55165
+ scopedToInstance: boolean()
55166
+ }).optional(),
54242
55167
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54243
- instanceMode: _enum(["single", "multiple"]),
55168
+ instanceMode: IntegrationInstanceModeSchema,
54244
55169
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
54245
55170
  kind: string(),
54246
55171
  /** True when `testInstance` really probes the remote. */
54247
- canTest: boolean()
55172
+ canTest: boolean(),
55173
+ /**
55174
+ * The kinds an instance can be of. Absent or one entry: nothing to choose; more than one: the
55175
+ * Add flow asks which first and sends it as `createInstance.kind`.
55176
+ */
55177
+ kinds: array(IntegrationInstanceKindSchema).optional(),
55178
+ /**
55179
+ * The provider accepts `createInstance.id` for an id that once existed (an adopted id, because
55180
+ * devices carry it). The UI then offers "restore under its old id" on Add. Absent means no.
55181
+ */
55182
+ allowRestoreId: boolean().optional(),
55183
+ /**
55184
+ * `createInstance` without an `id` works: the provider mints it. Absent means the caller must
55185
+ * send an id (the UI then mints an opaque one).
55186
+ */
55187
+ mintsId: boolean().optional()
54248
55188
  });
54249
55189
  var IntegrationInstanceStatusSchema = object({
54250
55190
  state: _enum([
@@ -54253,7 +55193,9 @@ var IntegrationInstanceStatusSchema = object({
54253
55193
  "error",
54254
55194
  "unknown"
54255
55195
  ]),
54256
- detail: string().optional()
55196
+ detail: string().optional(),
55197
+ /** A short human word for the state ("Signed in", "Token expired"); shown instead of `state`. */
55198
+ label: string().optional()
54257
55199
  });
54258
55200
  var IntegrationInstanceSchema = object({
54259
55201
  id: IntegrationInstanceIdSchema,
@@ -54261,13 +55203,18 @@ var IntegrationInstanceSchema = object({
54261
55203
  /** The addon's own rule (an URL is present, a client id is present...). */
54262
55204
  configured: boolean(),
54263
55205
  /**
54264
- * The instance's own on/off switch (D996): always present, derived from the record body
54265
- * (`enabled !== false`, so a row written before the field existed is on).
55206
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
55207
+ * so a row written before the field existed is on). Absent when the `integrations` registry
55208
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
54266
55209
  */
54267
- enabled: boolean(),
55210
+ enabled: boolean().optional(),
55211
+ /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
55212
+ kind: string().optional(),
54268
55213
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
54269
55214
  formValues: record(string(), unknown()),
54270
- status: IntegrationInstanceStatusSchema.optional()
55215
+ status: IntegrationInstanceStatusSchema.optional(),
55216
+ /** Epoch ms of the last probe of the remote that produced `status`; absent when never checked. */
55217
+ lastCheckedAt: number().optional()
54271
55218
  });
54272
55219
  var IntegrationInstancePatchSchema = object({
54273
55220
  id: IntegrationInstanceIdSchema,
@@ -54275,31 +55222,57 @@ var IntegrationInstancePatchSchema = object({
54275
55222
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54276
55223
  values: record(string(), unknown())
54277
55224
  });
54278
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
54279
- id: IntegrationInstanceIdSchema,
54280
- name: string().min(1)
54281
- }), object({ id: string() }), {
54282
- kind: "mutation",
54283
- auth: "admin"
54284
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54285
- kind: "mutation",
54286
- auth: "admin"
54287
- }), method(object({
54288
- id: IntegrationInstanceIdSchema,
54289
- enabled: boolean()
54290
- }), object({ ok: literal(true) }), {
54291
- kind: "mutation",
54292
- auth: "admin"
54293
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54294
- kind: "mutation",
54295
- auth: "admin"
54296
- }), optionalMethod(object({
54297
- id: IntegrationInstanceIdSchema.nullable(),
54298
- values: record(string(), unknown())
54299
- }), TestConnectionResultSchema$1, {
54300
- kind: "mutation",
54301
- auth: "admin"
54302
- });
55225
+ var integrationInstancesCapability = {
55226
+ name: "integration-instances",
55227
+ scope: "system",
55228
+ mode: "collection",
55229
+ methods: {
55230
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
55231
+ /** The form; `id: null` is the create form. */
55232
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
55233
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
55234
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
55235
+ /**
55236
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
55237
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
55238
+ */
55239
+ createInstance: method(object({
55240
+ id: IntegrationInstanceIdSchema.optional(),
55241
+ name: string().min(1),
55242
+ kind: string().min(1).optional()
55243
+ }), object({ id: string() }), {
55244
+ kind: "mutation",
55245
+ auth: "admin"
55246
+ }),
55247
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
55248
+ kind: "mutation",
55249
+ auth: "admin"
55250
+ }),
55251
+ /**
55252
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
55253
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
55254
+ */
55255
+ setInstanceEnabled: method(object({
55256
+ id: IntegrationInstanceIdSchema,
55257
+ enabled: boolean()
55258
+ }), object({ ok: literal(true) }), {
55259
+ kind: "mutation",
55260
+ auth: "admin"
55261
+ }),
55262
+ /** Delete the record and its keychain refs together. */
55263
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
55264
+ kind: "mutation",
55265
+ auth: "admin"
55266
+ }),
55267
+ testInstance: optionalMethod(object({
55268
+ id: IntegrationInstanceIdSchema.nullable(),
55269
+ values: record(string(), unknown())
55270
+ }), TestConnectionResultSchema$1, {
55271
+ kind: "mutation",
55272
+ auth: "admin"
55273
+ })
55274
+ }
55275
+ };
54303
55276
  /**
54304
55277
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54305
55278
  * session (server-initiated offer pattern, identical to the main
@@ -56098,6 +57071,11 @@ var LogEntrySchema = object({
56098
57071
  * flight, and not asking for the next slice ends the scan.
56099
57072
  */
56100
57073
  var LogReadQuerySchema = object({
57074
+ /**
57075
+ * Which destination INSTANCE answers (a destination addon may hold several records). Absent ⇒
57076
+ * the provider's first readable one, so a caller written before instances existed is unchanged.
57077
+ */
57078
+ instanceId: string().min(1).max(200).optional(),
56101
57079
  /** Correlates `cancelRead`. Caller-chosen, unique per in-flight read. */
56102
57080
  requestId: string().min(1).max(64).optional(),
56103
57081
  /** The device the line is about (`tags.deviceId`, numeric). */
@@ -56160,6 +57138,8 @@ var LogReadResultSchema = object({
56160
57138
  /** True when `cancelRead` ended this slice early. */
56161
57139
  cancelled: boolean().optional()
56162
57140
  });
57141
+ /** Names one destination instance; absent ⇒ the provider's first readable one. */
57142
+ var LogInstanceSelectorSchema = object({ instanceId: string().min(1).max(200).optional() });
56163
57143
  var LogReadCapabilitiesSchema = object({
56164
57144
  /** False ⇒ this destination only ships lines (console, forwarder, an unconfigured Loki). */
56165
57145
  readable: boolean(),
@@ -56178,7 +57158,7 @@ var LogReadCapabilitiesSchema = object({
56178
57158
  /** How far back the store reaches, when the provider knows (days). */
56179
57159
  retentionDays: number().nullable()
56180
57160
  });
56181
- method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(_void(), LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
57161
+ method(LogEntrySchema, _void(), { kind: "mutation" }), optionalMethod(LogInstanceSelectorSchema, LogReadCapabilitiesSchema, { auth: "admin" }), optionalMethod(LogReadQuerySchema, LogReadResultSchema, { auth: "admin" }), optionalMethod(object({ requestId: string().min(1).max(64) }), object({ cancelled: boolean() }), {
56182
57162
  kind: "mutation",
56183
57163
  auth: "admin"
56184
57164
  });
@@ -67750,6 +68730,49 @@ object({
67750
68730
  DeviceType.PetFeeder,
67751
68731
  DeviceType.Heater
67752
68732
  ].filter((type) => type !== DeviceType.Sensor);
68733
+ var PowerSourceRefusalReasonSchema = _enum([
68734
+ "no-power-source",
68735
+ "switch-missing",
68736
+ "switch-offline",
68737
+ "switch-unknown",
68738
+ "restart-in-progress",
68739
+ "switch-call-failed"
68740
+ ]);
68741
+ var PowerSourceActionResultSchema = discriminatedUnion("accepted", [object({ accepted: literal(true) }), object({
68742
+ accepted: literal(false),
68743
+ reason: PowerSourceRefusalReasonSchema,
68744
+ /** One line for the operator, naming the switch. */
68745
+ message: string()
68746
+ })]);
68747
+ var PowerSourceInfoSchema = object({
68748
+ /** False when the device has no power source linked; the rest is then empty. */
68749
+ linked: boolean(),
68750
+ switchDeviceId: number().nullable(),
68751
+ switchName: string().nullable(),
68752
+ /** The switch's on/off state, or null when it is unknown. Never false for unknown (D393). */
68753
+ switchOn: boolean().nullable(),
68754
+ switchOnline: boolean().nullable(),
68755
+ restartInProgress: boolean(),
68756
+ offSeconds: number().int()
68757
+ });
68758
+ object({
68759
+ /** Null while the switch has not reported: unknown is never `false` (D393). */
68760
+ switchOn: boolean().nullable(),
68761
+ offSeconds: number().int(),
68762
+ lastFetchedAt: number()
68763
+ });
68764
+ DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater;
68765
+ var deviceInput$1 = object({ deviceId: number().int().nonnegative() });
68766
+ systemMethod(deviceInput$1, PowerSourceInfoSchema, { auth: "admin" }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68767
+ kind: "mutation",
68768
+ auth: "admin"
68769
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68770
+ kind: "mutation",
68771
+ auth: "admin"
68772
+ }), systemMethod(deviceInput$1, PowerSourceActionResultSchema, {
68773
+ kind: "mutation",
68774
+ auth: "admin"
68775
+ });
67753
68776
  /**
67754
68777
  * Presence cap. Models HA `person.*` and `device_tracker.*` entities
67755
68778
  * on `DeviceType.Presence`. Read-only — no setters: presence is
@@ -76017,6 +77040,25 @@ function buildDescriptor(capName, kind) {
76017
77040
  * contributes one entry per bound cap present in this map.
76018
77041
  */
76019
77042
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
77043
+ /**
77044
+ * What a remote key is CALLED and what it LOOKS like, for every role (D963),
77045
+ * shared by the admin UI and the viewer. A role is data on the wire; each
77046
+ * client resolves its name from `label` (English and Italian side by side) and
77047
+ * its glyph from `icon`, a lucide id from the shared icon catalogue — the
77048
+ * server sends an id, a client maps it to its own icon set.
77049
+ *
77050
+ * `legend` is text printed on the key INSTEAD of a glyph (a digit has no
77051
+ * pictogram): a client that can draw text shows it, one that cannot falls back
77052
+ * to `icon`.
77053
+ */
77054
+ function digit(n) {
77055
+ return {
77056
+ label: t(n, n),
77057
+ icon: "hash",
77058
+ legend: n
77059
+ };
77060
+ }
77061
+ digit("0"), digit("1"), digit("2"), digit("3"), digit("4"), digit("5"), digit("6"), digit("7"), digit("8"), digit("9");
76020
77062
  DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
76021
77063
  var btn = (idSuffix, row, col, init) => ({
76022
77064
  idSuffix,
@@ -76144,6 +77186,34 @@ discriminatedUnion("kind", [object({
76144
77186
  kind: literal("pronto"),
76145
77187
  code: string()
76146
77188
  })]);
77189
+ /**
77190
+ * Propose a running threshold from a device's own power history (planning#405).
77191
+ *
77192
+ * Pure and deterministic: the same series gives the same answer. The series is
77193
+ * a HELD-VALUE step series — a point's value stands until the next point — which
77194
+ * is how device-history stores a gauge, so "time at a level" is exact, not a
77195
+ * count of samples.
77196
+ *
77197
+ * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77198
+ * near F. A device that is not near one level most of the time has no floor.
77199
+ * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77200
+ * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77201
+ * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77202
+ * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77203
+ * grid a person would type; stop dwell covers the longest pause; start dwell
77204
+ * covers the longest standby blip above T.
77205
+ * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77206
+ * run must hold exactly one true interval and nothing may flap outside.
77207
+ */
77208
+ var SECOND_MS = 1e3;
77209
+ var MINUTE_MS$1 = 60 * SECOND_MS;
77210
+ 24 * (60 * MINUTE_MS$1);
77211
+ 10 * MINUTE_MS$1;
77212
+ 30 * SECOND_MS;
77213
+ 60 * SECOND_MS;
77214
+ 20 * MINUTE_MS$1;
77215
+ 10 * SECOND_MS;
77216
+ 10 * SECOND_MS;
76147
77217
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
76148
77218
  SOURCE_CAPS.filter((cap) => cap !== "switch" && cap !== "motion");
76149
77219
  String.raw`rose\(active(\d+), changed(\d+), (\d+(?:\.\d+)?)\)`;
@@ -77685,6 +78755,13 @@ Object.freeze({
77685
78755
  access: "create",
77686
78756
  role: "admin"
77687
78757
  },
78758
+ "coreBlocks.proposeRunningThreshold": {
78759
+ capName: "core-blocks",
78760
+ capScope: "system",
78761
+ addonId: null,
78762
+ access: "view",
78763
+ role: "admin"
78764
+ },
77688
78765
  "coreBlocks.reportAutomationRun": {
77689
78766
  capName: "core-blocks",
77690
78767
  capScope: "system",
@@ -78196,6 +79273,13 @@ Object.freeze({
78196
79273
  access: "view",
78197
79274
  role: "admin"
78198
79275
  },
79276
+ "deviceExport.listInstances": {
79277
+ capName: "device-export",
79278
+ capScope: "system",
79279
+ addonId: null,
79280
+ access: "view",
79281
+ role: "admin"
79282
+ },
78199
79283
  "deviceExport.listSupportedDeviceKinds": {
78200
79284
  capName: "device-export",
78201
79285
  capScope: "system",
@@ -87168,6 +88252,11 @@ Object.freeze({
87168
88252
  form: "single",
87169
88253
  optional: false
87170
88254
  }],
88255
+ "coreBlocks.proposeRunningThreshold": [{
88256
+ name: "deviceId",
88257
+ form: "single",
88258
+ optional: false
88259
+ }],
87171
88260
  "cover.close": [{
87172
88261
  name: "deviceId",
87173
88262
  form: "single",
@@ -89831,99 +90920,6 @@ Object.freeze({
89831
90920
  "network-access": "ingress",
89832
90921
  "smtp-provider": "email"
89833
90922
  });
89834
- /**
89835
- * A saved Customize assignment (D936). The schema is the type: callers use
89836
- * `z.infer`, they do not restate the shape.
89837
- */
89838
- var OverrideSourceSchema = object({
89839
- addonId: string().min(1),
89840
- stableId: string().min(1),
89841
- cap: string().min(1),
89842
- fieldPath: string().min(1)
89843
- });
89844
- var CustomizeTransformDraftSchema = discriminatedUnion("kind", [
89845
- object({ kind: literal("identity") }),
89846
- object({ kind: literal("invert") }),
89847
- object({
89848
- kind: literal("threshold"),
89849
- comparison: _enum(["gte", "lte"]),
89850
- threshold: number(),
89851
- startDwellMs: number().nonnegative(),
89852
- stopDwellMs: number().nonnegative()
89853
- }),
89854
- object({
89855
- kind: literal("linear"),
89856
- scale: number(),
89857
- offset: number(),
89858
- clampMin: number().optional(),
89859
- clampMax: number().optional()
89860
- }),
89861
- object({
89862
- kind: literal("enum-map"),
89863
- mapping: record(string(), string().nullable())
89864
- }),
89865
- object({ kind: literal("number") })
89866
- ]);
89867
- var ScalarOverrideDraftSchema = object({
89868
- kind: literal("scalar"),
89869
- cap: string().min(1),
89870
- targetId: string().min(1),
89871
- source: OverrideSourceSchema,
89872
- transform: CustomizeTransformDraftSchema
89873
- });
89874
- var KeyedArrayOverrideDraftSchema = object({
89875
- kind: literal("keyedArray"),
89876
- cap: string().min(1),
89877
- targetId: string().min(1),
89878
- key: string().min(1),
89879
- label: string().min(1),
89880
- fieldPath: string().min(1),
89881
- source: OverrideSourceSchema,
89882
- transform: CustomizeTransformDraftSchema
89883
- });
89884
- var PulseOverrideDraftSchema = object({
89885
- kind: literal("pulse"),
89886
- cap: string().min(1),
89887
- targetId: string().min(1),
89888
- enabled: boolean(),
89889
- debounceMs: number().nonnegative(),
89890
- edges: array(_enum([
89891
- "rising",
89892
- "button",
89893
- "native-event"
89894
- ])).min(1).optional(),
89895
- sources: array(OverrideSourceSchema).min(1)
89896
- });
89897
- var SpanSourceDraftSchema = OverrideSourceSchema.extend({ mode: _enum([
89898
- "in-addition",
89899
- "confirm",
89900
- "replace"
89901
- ]).optional() });
89902
- discriminatedUnion("kind", [
89903
- ScalarOverrideDraftSchema,
89904
- KeyedArrayOverrideDraftSchema,
89905
- PulseOverrideDraftSchema,
89906
- object({
89907
- kind: literal("span"),
89908
- cap: string().min(1),
89909
- targetId: string().min(1),
89910
- timeoutMs: number().nonnegative(),
89911
- cooldownMs: number().nonnegative().optional(),
89912
- sources: array(SpanSourceDraftSchema)
89913
- })
89914
- ]);
89915
- object({
89916
- targetId: string().min(1),
89917
- configured: boolean(),
89918
- source: _enum(["native", "assigned"]),
89919
- state: _enum([
89920
- "active",
89921
- "stale",
89922
- "released",
89923
- "unavailable"
89924
- ]),
89925
- reason: string().nullable()
89926
- });
89927
90923
  var G711_SCALE_CORRECTION_DB = {
89928
90924
  PCMU: 20 * Math.log10(4),
89929
90925
  PCMA: 20 * Math.log10(8)
@@ -138478,6 +139474,133 @@ function carryForward(base, existing, keys) {
138478
139474
  return out;
138479
139475
  }
138480
139476
  //#endregion
139477
+ //#region src/hap-export-records.ts
139478
+ /**
139479
+ * What one HomeKit bridge exposes (D985, D996): a `hap-bridge-exports` row per bridge instance,
139480
+ * under the instance's own id, holds the devices it mirrors (with their per-device export
139481
+ * settings) and the actions it publishes as momentary switches. The identity a controller pairs
139482
+ * with is the sibling `hap-bridges` row; this row is what that bridge CARRIES.
139483
+ *
139484
+ * It replaces the `exposed` and `exposedActions` addon settings. The migration moved them; the
139485
+ * addon reads this record and nothing else.
139486
+ */
139487
+ var ExportDeviceSettingsSchema = object({
139488
+ multiTierService: boolean().optional(),
139489
+ streamPreference: string(),
139490
+ useBridge: boolean().optional(),
139491
+ allowTranscode: boolean().optional(),
139492
+ keepClips: boolean().optional(),
139493
+ clipRetentionDays: number().optional()
139494
+ });
139495
+ var MapperKindSchema = _enum(["camera", "generic"]);
139496
+ var ExposedConfigEntrySchema = object({
139497
+ deviceId: string(),
139498
+ displayName: string(),
139499
+ mapperKind: MapperKindSchema,
139500
+ capabilities: array(string()).optional(),
139501
+ childAccessoryUuids: array(string()).optional(),
139502
+ addedAt: number().optional(),
139503
+ settings: ExportDeviceSettingsSchema.optional()
139504
+ });
139505
+ var ActionExportEntrySchema = object({
139506
+ actionId: string(),
139507
+ displayName: string(),
139508
+ addedAt: number()
139509
+ });
139510
+ var HapBridgeExportsBodySchema = object({
139511
+ name: string().min(1),
139512
+ devices: array(ExposedConfigEntrySchema),
139513
+ actions: array(ActionExportEntrySchema)
139514
+ });
139515
+ /** The label of every exposure record: it is the instance's, not an operator's name. */
139516
+ var HAP_EXPOSURE_NAME = "HomeKit exposure";
139517
+ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139518
+ title: "HomeKit exposure",
139519
+ nameField: "name",
139520
+ schema: HapBridgeExportsBodySchema,
139521
+ writeTrigger: "an operator exposes or unexposes a device or action to HomeKit"
139522
+ });
139523
+ /** The settings keys that moved into the record; the migrations name them. */
139524
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139525
+ //#endregion
139526
+ //#region src/hap-instance-kinds.ts
139527
+ /**
139528
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139529
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139530
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139531
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139532
+ * (`hapPersistDirOf`). The default instance is keyed by the
139533
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139534
+ * controller that paired before keeps working.
139535
+ */
139536
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139537
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139538
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139539
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139540
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139541
+ function hapPersistDirOf(instanceId) {
139542
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139543
+ }
139544
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139545
+ title: "HomeKit bridge",
139546
+ nameField: "name",
139547
+ schema: object({
139548
+ name: string().min(1),
139549
+ username: string().min(1),
139550
+ uuid: string().min(1),
139551
+ pincode: string().min(1).meta({ secret: true }),
139552
+ enabled: boolean().optional()
139553
+ })
139554
+ });
139555
+ function identityOfBody(body) {
139556
+ return {
139557
+ username: body.username,
139558
+ uuid: body.uuid,
139559
+ pincode: body.pincode
139560
+ };
139561
+ }
139562
+ //#endregion
139563
+ //#region src/hap-identity.ts
139564
+ /**
139565
+ * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139566
+ * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139567
+ * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139568
+ * A legacy identity without a record means the migration did not finish, and minting then would
139569
+ * unpair every controller, so the addon refuses to boot with the reason.
139570
+ */
139571
+ /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139572
+ async function resolveBridgeIdentity(fixedPin, ports) {
139573
+ const stored = await ports.readRecord();
139574
+ if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139575
+ if (stored.kind === "resolved") {
139576
+ if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139577
+ await ports.patchPincode(fixedPin);
139578
+ return {
139579
+ identity: identityOfBody({
139580
+ ...stored.body,
139581
+ pincode: fixedPin
139582
+ }),
139583
+ minted: false
139584
+ };
139585
+ }
139586
+ return {
139587
+ identity: identityOfBody(stored.body),
139588
+ minted: false
139589
+ };
139590
+ }
139591
+ if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139592
+ const fresh = ports.mint();
139593
+ const body = fixedPin === null ? fresh : {
139594
+ ...fresh,
139595
+ pincode: fixedPin
139596
+ };
139597
+ await ports.putFresh(body);
139598
+ return {
139599
+ identity: identityOfBody(body),
139600
+ minted: true
139601
+ };
139602
+ }
139603
+ //#endregion
138481
139604
  //#region src/migrations/hub-node-fields.ts
138482
139605
  /**
138483
139606
  * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
@@ -138548,40 +139671,248 @@ async function moveFixedPinToKeychain(ports) {
138548
139671
  };
138549
139672
  }
138550
139673
  //#endregion
139674
+ //#region src/migrations/exposure-to-record.ts
139675
+ /**
139676
+ * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
139677
+ * their per-device settings; `exposedActions`: the actions it publishes) move into the
139678
+ * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
139679
+ *
139680
+ * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
139681
+ * compare it with what the settings carried; a record that does not hold the same lists
139682
+ * throws and the settings are kept. An existing record is never overwritten.
139683
+ * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
139684
+ * rows, and only while the record holds exactly what they carry. A record that differs (the
139685
+ * operator edited the lists since) keeps the old keys, which nothing reads any more.
139686
+ *
139687
+ * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
139688
+ * way, which is what the boot sweep did to it anyway.
139689
+ */
139690
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
139691
+ function canonical(value) {
139692
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
139693
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
139694
+ return JSON.stringify(value) ?? "null";
139695
+ }
139696
+ function parsedList(value, parse) {
139697
+ if (!Array.isArray(value)) return [];
139698
+ const kept = [];
139699
+ for (const entry of value) {
139700
+ const parsed = parse(entry);
139701
+ if (parsed.success) kept.push(parsed.data);
139702
+ }
139703
+ return kept;
139704
+ }
139705
+ /** The record body the legacy settings describe. */
139706
+ function exposureBodyFrom(stored) {
139707
+ return {
139708
+ name: HAP_EXPOSURE_NAME,
139709
+ devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
139710
+ actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
139711
+ };
139712
+ }
139713
+ function sameLists(a, b) {
139714
+ return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
139715
+ }
139716
+ async function moveExposureToRecord(ports) {
139717
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139718
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
139719
+ outcome: "already-done",
139720
+ summary: { moved: false }
139721
+ };
139722
+ const body = exposureBodyFrom(stored);
139723
+ const put = await ports.putExposure(body);
139724
+ const held = await ports.readExposure();
139725
+ if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
139726
+ if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
139727
+ return put === "created" ? {
139728
+ outcome: "done",
139729
+ summary: {
139730
+ moved: true,
139731
+ devices: body.devices.length
139732
+ }
139733
+ } : {
139734
+ outcome: "already-done",
139735
+ summary: { moved: false }
139736
+ };
139737
+ }
139738
+ var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
139739
+ async function planDropExposureKeys(ports) {
139740
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139741
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
139742
+ if (present.length === 0) return { edits: [] };
139743
+ const held = await ports.readExposure();
139744
+ if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
139745
+ return { edits: [{
139746
+ op: "deleteKeys",
139747
+ scope: ADDON_SETTINGS_TABLE,
139748
+ keys: present.map(rowId),
139749
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
139750
+ addonId: HAP_DEFAULT_INSTANCE_ID,
139751
+ key,
139752
+ value: stored[key]
139753
+ }])))
139754
+ }] };
139755
+ }
139756
+ //#endregion
139757
+ //#region src/migrations/identity-to-instance.ts
139758
+ /**
139759
+ * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
139760
+ * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
139761
+ * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
139762
+ * record back and comparing, field by field, before it reports `done`.
139763
+ *
139764
+ * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
139765
+ * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
139766
+ * already there and names the same bridge (username, uuid) the leftover old identity of an
139767
+ * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
139768
+ * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
139769
+ * one (a new identity unpairs every controller).
139770
+ */
139771
+ async function moveIdentityToDefaultInstance(ports) {
139772
+ const legacy = await ports.readLegacyIdentity();
139773
+ if (legacy === null) return {
139774
+ outcome: "already-done",
139775
+ summary: { moved: false }
139776
+ };
139777
+ const name = (await ports.readBridgeName()).trim();
139778
+ const body = {
139779
+ name: name.length > 0 ? name : "CamStack Bridge",
139780
+ username: legacy.username,
139781
+ uuid: legacy.uuid,
139782
+ pincode: legacy.pincode
139783
+ };
139784
+ const put = await ports.putDefaultRecord(body);
139785
+ const held = await ports.readDefaultRecord();
139786
+ if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
139787
+ if (put === "exists") {
139788
+ if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
139789
+ await ports.clearLegacyIdentity();
139790
+ return {
139791
+ outcome: "done",
139792
+ summary: {
139793
+ moved: false,
139794
+ cleared: true
139795
+ }
139796
+ };
139797
+ }
139798
+ if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
139799
+ await ports.clearLegacyIdentity();
139800
+ return {
139801
+ outcome: "done",
139802
+ summary: { moved: true }
139803
+ };
139804
+ }
139805
+ function sameIdentity(a, b) {
139806
+ return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
139807
+ }
139808
+ /**
139809
+ * The identity a settings value describes, secrets resolved; null when it is not a complete
139810
+ * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
139811
+ * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
139812
+ */
139813
+ function legacyIdentityOf(value) {
139814
+ if (typeof value !== "object" || value === null) return null;
139815
+ const username = Reflect.get(value, "username");
139816
+ const uuid = Reflect.get(value, "uuid");
139817
+ const pincode = Reflect.get(value, "pincode");
139818
+ if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
139819
+ if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
139820
+ return {
139821
+ username,
139822
+ uuid,
139823
+ pincode
139824
+ };
139825
+ }
139826
+ //#endregion
138551
139827
  //#region src/migrations/index.ts
138552
139828
  var EXPORT_HAP_ID = "export-hap";
139829
+ var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139830
+ var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139831
+ var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139832
+ var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
138553
139833
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
138554
- var ADDON_MIGRATIONS = [{
138555
- meta: {
138556
- id: "export-hap/2026-11-03-interface-name-per-node",
138557
- owner: EXPORT_HAP_ID,
138558
- level: "addon-state",
138559
- seq: 1,
138560
- dependsOn: [],
138561
- store: "settings",
138562
- scope: "per-node",
138563
- onFailure: "tolerate",
138564
- bodyKind: "plan",
138565
- description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
138566
- fixtureMark: "the bridge name the migration does not know"
138567
- },
138568
- plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
138569
- }, {
138570
- meta: {
138571
- id: "export-hap/2026-11-03-fixed-pin-to-keychain",
138572
- owner: EXPORT_HAP_ID,
138573
- level: "addon-state",
138574
- seq: 2,
138575
- dependsOn: [],
138576
- store: "settings",
138577
- scope: "cluster",
138578
- onFailure: "tolerate",
138579
- bodyKind: "procedure",
138580
- description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
138581
- fixtureMark: "the bridge name the migration does not know"
138582
- },
138583
- procedure: moveFixedPinToKeychain
138584
- }];
139834
+ var ADDON_MIGRATIONS = [
139835
+ {
139836
+ meta: {
139837
+ id: INTERFACE_NAME_PER_NODE_ID,
139838
+ owner: EXPORT_HAP_ID,
139839
+ level: "addon-state",
139840
+ seq: 1,
139841
+ dependsOn: [],
139842
+ store: "settings",
139843
+ scope: "per-node",
139844
+ onFailure: "tolerate",
139845
+ bodyKind: "plan",
139846
+ description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
139847
+ fixtureMark: "the bridge name the migration does not know"
139848
+ },
139849
+ plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
139850
+ },
139851
+ {
139852
+ meta: {
139853
+ id: FIXED_PIN_TO_KEYCHAIN_ID,
139854
+ owner: EXPORT_HAP_ID,
139855
+ level: "addon-state",
139856
+ seq: 2,
139857
+ dependsOn: [],
139858
+ store: "settings",
139859
+ scope: "cluster",
139860
+ onFailure: "tolerate",
139861
+ bodyKind: "procedure",
139862
+ description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
139863
+ fixtureMark: "the bridge name the migration does not know"
139864
+ },
139865
+ procedure: moveFixedPinToKeychain
139866
+ },
139867
+ {
139868
+ meta: {
139869
+ id: IDENTITY_TO_INSTANCE_ID,
139870
+ owner: EXPORT_HAP_ID,
139871
+ level: "addon-state",
139872
+ seq: 3,
139873
+ dependsOn: [],
139874
+ store: "settings",
139875
+ scope: "cluster",
139876
+ onFailure: "block-owner",
139877
+ bodyKind: "procedure",
139878
+ description: "Move the bridge identity (username, uuid, setup code) into the default HomeKit instance record, unchanged, then clear the old setting and its keychain entry",
139879
+ fixtureMark: "the bridge name the migration does not know"
139880
+ },
139881
+ procedure: moveIdentityToDefaultInstance
139882
+ },
139883
+ {
139884
+ meta: {
139885
+ id: EXPOSURE_TO_RECORD_ID,
139886
+ owner: EXPORT_HAP_ID,
139887
+ level: "addon-state",
139888
+ seq: 4,
139889
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
139890
+ store: "settings",
139891
+ scope: "cluster",
139892
+ onFailure: "block-owner",
139893
+ bodyKind: "procedure",
139894
+ description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
139895
+ fixtureMark: "the bridge name the migration does not know"
139896
+ },
139897
+ procedure: moveExposureToRecord
139898
+ },
139899
+ {
139900
+ meta: {
139901
+ id: "export-hap/2026-11-04-drop-exposure-keys",
139902
+ owner: EXPORT_HAP_ID,
139903
+ level: "addon-state",
139904
+ seq: 5,
139905
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
139906
+ store: "settings",
139907
+ scope: "cluster",
139908
+ onFailure: "tolerate",
139909
+ bodyKind: "plan",
139910
+ description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
139911
+ fixtureMark: "the bridge name the migration does not know"
139912
+ },
139913
+ plan: planDropExposureKeys
139914
+ }
139915
+ ];
138585
139916
  //#endregion
138586
139917
  //#region src/hap-setup-uri.ts
138587
139918
  function errMsg$15(e) {
@@ -157784,9 +159115,8 @@ function syncStateToJson(map) {
157784
159115
  * Operator flow:
157785
159116
  * 1. Install + enable the addon (hub-only, group `export-hap`).
157786
159117
  * 2. On first boot the addon generates a random pincode + bridge
157787
- * MAC username and persists them on `this.config.identity` via
157788
- * `updateGlobalSettings` (no JSON sidecar files — the kernel
157789
- * addon-store IS the cache).
159118
+ * MAC username and persists them in the default instance record
159119
+ * (`hap-bridges`, no JSON sidecar files).
157790
159120
  * 3. The setup URI (`X-HM://…`) is logged AND surfaced via the
157791
159121
  * `getStatus` cap method so the wizard UI can render the QR.
157792
159122
  * 4. Operator opens iOS Home → + → scan QR → enter pincode.
@@ -157924,13 +159254,6 @@ var DEFAULT_CONFIG = {
157924
159254
  fixedPin: "",
157925
159255
  interfaceName: "",
157926
159256
  clipRetentionDays: 14,
157927
- identity: {
157928
- username: "",
157929
- pincode: "",
157930
- uuid: ""
157931
- },
157932
- exposed: [],
157933
- exposedActions: [],
157934
159257
  exportSyncState: {}
157935
159258
  };
157936
159259
  var BANNED_PINCODES = new Set([
@@ -157969,12 +159292,27 @@ function buildBridgeUuid(bridgeName) {
157969
159292
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
157970
159293
  }
157971
159294
  var ExportHapAddon = class extends BaseAddon {
157972
- /** The bridge setup code pairs a controller: a credential, kept in the keychain (D787). */
159295
+ /**
159296
+ * The old `identity.pincode` secret: declared only so the identity migration can release its
159297
+ * keychain entry when it clears the old setting. The identity itself is a record now.
159298
+ */
157973
159299
  secretStatePaths = ["identity.pincode"];
157974
159300
  exposed = /* @__PURE__ */ new Map();
157975
159301
  /** The exported actions — switches beside the devices (D968). */
157976
159302
  actionExports = null;
157977
159303
  lastError;
159304
+ /** The HomeKit instances (D985): one record per bridge identity. */
159305
+ instances = null;
159306
+ /**
159307
+ * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159308
+ * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159309
+ * boot and written through on every change; this addon is the record's only writer.
159310
+ */
159311
+ exposure = {
159312
+ name: HAP_EXPOSURE_NAME,
159313
+ devices: [],
159314
+ actions: []
159315
+ };
157978
159316
  /** Shared HAP setup code applied to every published accessory. */
157979
159317
  pincode = "";
157980
159318
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
@@ -158030,8 +159368,31 @@ var ExportHapAddon = class extends BaseAddon {
158030
159368
  super({ ...DEFAULT_CONFIG });
158031
159369
  }
158032
159370
  async onInitialize() {
159371
+ const records = this.ctx.records;
159372
+ if (records === void 0) throw new Error("export-hap needs ctx.records — check execution.placement (hub-only)");
159373
+ await records.declare({
159374
+ "hap-bridges": hapBridgesKind,
159375
+ "hap-bridge-exports": hapBridgeExportsKind
159376
+ });
159377
+ this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159378
+ description: {
159379
+ role: "services",
159380
+ instanceMode: "single",
159381
+ kind: "bridge",
159382
+ canTest: false
159383
+ },
159384
+ formSchema: () => this.schema({ sections: [] }),
159385
+ initialBody: (name) => ({
159386
+ name,
159387
+ username: generateUsername(),
159388
+ uuid: buildBridgeUuid(name),
159389
+ pincode: generatePincode()
159390
+ }),
159391
+ configured: (body) => body.username !== "" && body.pincode !== ""
159392
+ });
158033
159393
  await this.migrateSettings();
158034
159394
  const identity = await this.ensureIdentity();
159395
+ await this.loadExposure();
158035
159396
  this.pincode = identity.pincode;
158036
159397
  this.bind = this.config.interfaceName || void 0;
158037
159398
  this.bridgeHost = new BridgeHost({
@@ -158042,7 +159403,7 @@ var ExportHapAddon = class extends BaseAddon {
158042
159403
  logger: this.ctx.logger
158043
159404
  });
158044
159405
  try {
158045
- await initHapStorage(node_path.join(this.ctx.dataDir, "hap-store"));
159406
+ await initHapStorage(node_path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
158046
159407
  } catch (err) {
158047
159408
  this.lastError = errMsg(err);
158048
159409
  this.ctx.logger.error("export-hap: HAP storage init failed", { meta: { error: this.lastError } });
@@ -158068,12 +159429,12 @@ var ExportHapAddon = class extends BaseAddon {
158068
159429
  });
158069
159430
  await this.serveHksvClipPlanes();
158070
159431
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
158071
- const cleaned = this.config.exposed.filter((entry) => {
159432
+ const cleaned = this.exposure.devices.filter((entry) => {
158072
159433
  if (validKinds.has(entry.mapperKind)) return true;
158073
159434
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
158074
159435
  return false;
158075
159436
  });
158076
- if (cleaned.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: cleaned });
159437
+ if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
158077
159438
  for (const entry of cleaned) {
158078
159439
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
158079
159440
  try {
@@ -158106,8 +159467,8 @@ var ExportHapAddon = class extends BaseAddon {
158106
159467
  }
158107
159468
  await unpublishAccessory(accessory, this.ctx.logger);
158108
159469
  },
158109
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
158110
- }, this.config.exposedActions ?? []);
159470
+ persist: (entries) => this.setExposedActions(entries)
159471
+ }, this.exposure.actions);
158111
159472
  await this.actionExports.attachAll();
158112
159473
  await this.actionExports.reconcile();
158113
159474
  this.ctx.addDisposer(async () => {
@@ -158119,8 +159480,10 @@ var ExportHapAddon = class extends BaseAddon {
158119
159480
  this.subscribeDeviceReadyForReconcile();
158120
159481
  this.subscribeStorageLocationsForClips();
158121
159482
  this.disposeSharedRebuildTimers();
159483
+ const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
158122
159484
  const provider = {
158123
- getStatus: async () => {
159485
+ getStatus: async (input) => {
159486
+ ownInstance(statusInstanceOf(input));
158124
159487
  const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
158125
159488
  const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
158126
159489
  const setup = this.buildSetupBlock();
@@ -158131,19 +159494,38 @@ var ExportHapAddon = class extends BaseAddon {
158131
159494
  ...setup ? { setup } : {}
158132
159495
  };
158133
159496
  },
158134
- listSupportedDeviceKinds: async () => [...HAP_EXPORTABLE_DEVICE_TYPES],
158135
- listExposedDevices: async () => Array.from(this.exposed.entries()).map(([deviceId, m]) => {
158136
- const entry = this.config.exposed.find((e) => e.deviceId === deviceId);
158137
- return {
158138
- deviceId,
158139
- exposedAs: m.accessory.displayName,
158140
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
158141
- };
158142
- }),
158143
- exposeDevice: async ({ deviceId, capabilities }) => this.exposeDevice(deviceId, capabilities),
158144
- unexposeDevice: async ({ deviceId }) => this.unexposeDevice(deviceId),
159497
+ listInstances: async () => [{
159498
+ instanceId: EXPORT_HAP_ADDON_ID,
159499
+ name: "HomeKit",
159500
+ enabled: true,
159501
+ kind: "hap-bridge"
159502
+ }],
159503
+ listSupportedDeviceKinds: async ({ instanceId }) => {
159504
+ ownInstance(instanceId);
159505
+ return [...HAP_EXPORTABLE_DEVICE_TYPES];
159506
+ },
159507
+ listExposedDevices: async ({ instanceId }) => {
159508
+ ownInstance(instanceId);
159509
+ return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159510
+ const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159511
+ return {
159512
+ deviceId,
159513
+ exposedAs: m.accessory.displayName,
159514
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159515
+ };
159516
+ });
159517
+ },
159518
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159519
+ ownInstance(instanceId);
159520
+ return this.exposeDevice(deviceId, capabilities);
159521
+ },
159522
+ unexposeDevice: async ({ instanceId, deviceId }) => {
159523
+ ownInstance(instanceId);
159524
+ return this.unexposeDevice(deviceId);
159525
+ },
158145
159526
  listSupportedEntityKinds: async () => ["device", "action"],
158146
- listExposedEntities: async () => {
159527
+ listExposedEntities: async ({ instanceId }) => {
159528
+ ownInstance(instanceId);
158147
159529
  await this.actionExports?.reconcile();
158148
159530
  return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
158149
159531
  entity: {
@@ -158153,12 +159535,14 @@ var ExportHapAddon = class extends BaseAddon {
158153
159535
  exposedAs: m.accessory.displayName
158154
159536
  })), ...this.actionExports?.list() ?? []];
158155
159537
  },
158156
- exposeEntity: async ({ entity }) => {
159538
+ exposeEntity: async ({ instanceId, entity }) => {
159539
+ ownInstance(instanceId);
158157
159540
  if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
158158
159541
  if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
158159
159542
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158160
159543
  },
158161
- unexposeEntity: async ({ entity }) => {
159544
+ unexposeEntity: async ({ instanceId, entity }) => {
159545
+ ownInstance(instanceId);
158162
159546
  if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
158163
159547
  if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
158164
159548
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
@@ -158177,54 +159561,95 @@ var ExportHapAddon = class extends BaseAddon {
158177
159561
  thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
158178
159562
  clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
158179
159563
  });
158180
- return [{
158181
- capability: deviceExportCapability,
158182
- provider
158183
- }, {
158184
- capability: videoclipsCapability,
158185
- provider: clipsProvider
158186
- }];
159564
+ return [
159565
+ {
159566
+ capability: deviceExportCapability,
159567
+ provider
159568
+ },
159569
+ {
159570
+ capability: videoclipsCapability,
159571
+ provider: clipsProvider
159572
+ },
159573
+ {
159574
+ capability: integrationInstancesCapability,
159575
+ provider: this.requireInstances().toProvider()
159576
+ }
159577
+ ];
158187
159578
  }
158188
159579
  async onConfigChanged() {
158189
- if (this.config.fixedPin && isValidPincode(this.config.fixedPin) && this.config.identity.pincode !== this.config.fixedPin && this.config.identity.username !== "") {
158190
- const updated = {
158191
- username: this.config.identity.username,
158192
- uuid: this.config.identity.uuid,
158193
- pincode: this.config.fixedPin
158194
- };
158195
- await this.updateGlobalSettings({ identity: updated });
158196
- }
159580
+ const fixedPin = this.config.fixedPin;
159581
+ if (!fixedPin || !isValidPincode(fixedPin)) return;
159582
+ const handle = this.requireRecords().kind(hapBridgesKind);
159583
+ const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159584
+ if (row === null || row.data.pincode === fixedPin) return;
159585
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159586
+ }
159587
+ requireInstances() {
159588
+ if (this.instances === null) throw new Error("export-hap: instances are not initialised");
159589
+ return this.instances;
159590
+ }
159591
+ requireRecords() {
159592
+ const records = this.ctx.records;
159593
+ if (records === void 0) throw new Error("export-hap: records are not available");
159594
+ return records;
159595
+ }
159596
+ /** The ports the identity migration reads and writes through. */
159597
+ identityMigrationPorts() {
159598
+ const handle = this.requireRecords().kind(hapBridgesKind);
159599
+ return {
159600
+ readLegacyIdentity: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]),
159601
+ clearLegacyIdentity: () => this.updateGlobalSettingsAsOperator({ identity: null }),
159602
+ readBridgeName: async () => {
159603
+ const name = (await this.resolveGlobalStore())["bridgeName"];
159604
+ return typeof name === "string" ? name : "";
159605
+ },
159606
+ putDefaultRecord: async (body) => {
159607
+ if (await handle.get("export-hap") !== null) return "exists";
159608
+ try {
159609
+ await handle.put({
159610
+ id: HAP_DEFAULT_INSTANCE_ID,
159611
+ data: body
159612
+ }, { ifRev: 0 });
159613
+ } catch (err) {
159614
+ if (err instanceof RevConflictError) return "exists";
159615
+ throw err;
159616
+ }
159617
+ return "created";
159618
+ },
159619
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
159620
+ };
158197
159621
  }
158198
- /**
158199
- * Resolve the persistent bridge identity. Empty `username` is the
158200
- * "first boot" sentinel — generate fresh + persist. On subsequent
158201
- * boots the persisted record is reused. An operator-supplied
158202
- * `fixedPin` overrides the persisted pincode (useful for CI replay)
158203
- * but never the username/uuid (those drive the iOS pairing record).
158204
- */
159622
+ /** The identity of the default instance; see `resolveBridgeIdentity`. */
158205
159623
  async ensureIdentity() {
158206
- const current = this.config.identity;
158207
- const fixedPin = this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null;
158208
- if (current.username !== "" && current.uuid !== "" && current.pincode !== "") {
158209
- if (fixedPin && fixedPin !== current.pincode) {
158210
- const updated = {
158211
- username: current.username,
158212
- uuid: current.uuid,
158213
- pincode: fixedPin
158214
- };
158215
- await this.updateGlobalSettings({ identity: updated });
158216
- return updated;
158217
- }
158218
- return current;
158219
- }
158220
- const fresh = {
158221
- username: generateUsername(),
158222
- pincode: fixedPin ?? generatePincode(),
158223
- uuid: buildBridgeUuid(this.config.bridgeName)
158224
- };
158225
- await this.updateGlobalSettings({ identity: fresh });
158226
- this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: fresh.username } });
158227
- return fresh;
159624
+ const handle = this.requireRecords().kind(hapBridgesKind);
159625
+ const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
159626
+ readRecord: async () => {
159627
+ const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159628
+ if (resolved === null) return { kind: "absent" };
159629
+ return resolved.secrets === "resolved" ? {
159630
+ kind: "resolved",
159631
+ body: resolved.body
159632
+ } : { kind: "unavailable" };
159633
+ },
159634
+ legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159635
+ patchPincode: async (pincode) => {
159636
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159637
+ },
159638
+ putFresh: async (body) => {
159639
+ await handle.put({
159640
+ id: HAP_DEFAULT_INSTANCE_ID,
159641
+ data: body
159642
+ }, { ifRev: 0 });
159643
+ },
159644
+ mint: () => ({
159645
+ name: this.config.bridgeName,
159646
+ username: generateUsername(),
159647
+ uuid: buildBridgeUuid(this.config.bridgeName),
159648
+ pincode: generatePincode()
159649
+ })
159650
+ });
159651
+ if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159652
+ return identity;
158228
159653
  }
158229
159654
  /**
158230
159655
  * Build the generic `device-export` `setup` block surfaced via
@@ -158234,7 +159659,7 @@ var ExportHapAddon = class extends BaseAddon {
158234
159659
  * until the bridge has booted and produced both values.
158235
159660
  */
158236
159661
  buildSetupBlock() {
158237
- const setupCode = this.config.identity.pincode;
159662
+ const setupCode = this.pincode;
158238
159663
  if (!setupCode) return null;
158239
159664
  const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
158240
159665
  return {
@@ -158268,7 +159693,7 @@ var ExportHapAddon = class extends BaseAddon {
158268
159693
  const mapperKind = pickMapperKind(summary?.type);
158269
159694
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
158270
159695
  const displayName = summary?.name ?? `Device ${deviceId}`;
158271
- const previous = this.config.exposed.find((e) => e.deviceId === deviceId);
159696
+ const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
158272
159697
  const rebuilt = {
158273
159698
  deviceId,
158274
159699
  displayName,
@@ -158285,9 +159710,9 @@ var ExportHapAddon = class extends BaseAddon {
158285
159710
  ...baseEntry,
158286
159711
  childAccessoryUuids: attached.childAccessoryUuids
158287
159712
  };
158288
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
159713
+ const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
158289
159714
  next.push(finalEntry);
158290
- await this.updateGlobalSettings({ exposed: next });
159715
+ await this.setExposedDevices(next);
158291
159716
  if (Number.isFinite(numericId)) {
158292
159717
  const fp = await this.computeExportFingerprint(numericId);
158293
159718
  if (fp !== null) await this.persistFingerprint(numericId, fp);
@@ -158303,8 +159728,8 @@ var ExportHapAddon = class extends BaseAddon {
158303
159728
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158304
159729
  const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
158305
159730
  await this.detachMapper(deviceId);
158306
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
158307
- if (next.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: next });
159731
+ const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159732
+ if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
158308
159733
  if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
158309
159734
  await this.forgetFingerprint(numericId);
158310
159735
  this.hksvBuilds.forget(numericId);
@@ -158667,7 +160092,9 @@ var ExportHapAddon = class extends BaseAddon {
158667
160092
  async migrateSettings() {
158668
160093
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
158669
160094
  readStored: (keys) => readRawKeys((key) => this.readStoredGlobalKey(key), "export-hap", keys),
158670
- storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin })
160095
+ storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin }),
160096
+ ...this.identityMigrationPorts(),
160097
+ ...this.exposureMigrationPorts()
158671
160098
  }))).applied.length > 0) await this.resolveConfig();
158672
160099
  }
158673
160100
  globalSettingsSchema() {
@@ -158725,7 +160152,7 @@ var ExportHapAddon = class extends BaseAddon {
158725
160152
  const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
158726
160153
  const name = entry?.displayName ?? `Device ${deviceId}`;
158727
160154
  const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
158728
- const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.config.identity.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.config.identity.pincode}.`;
160155
+ const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.pincode}.`;
158729
160156
  const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
158730
160157
  let qrValue = "";
158731
160158
  if (qrSource) try {
@@ -158852,7 +160279,7 @@ var ExportHapAddon = class extends BaseAddon {
158852
160279
  type: "qr-code",
158853
160280
  key: "__hap-pair-qr",
158854
160281
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
158855
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.config.identity.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.config.identity.pincode}.`,
160282
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.pincode}.`,
158856
160283
  value: qrValue,
158857
160284
  size: 192,
158858
160285
  alt: `HomeKit pairing QR for ${name}`,
@@ -159016,16 +160443,72 @@ var ExportHapAddon = class extends BaseAddon {
159016
160443
  const planes = this.hksvClipPlanes;
159017
160444
  return `/addon/${EXPORT_HAP_ADDON_ID}/${kind === "media" ? planes?.mediaPrefix ?? "hksv-clip" : planes?.thumbPrefix ?? "hksv-clip-thumb"}/${String(deviceId)}/${stem}.${kind === "media" ? "mp4" : "jpg"}`;
159018
160445
  }
160446
+ /** The exposure record's handle: one row per bridge instance, under the instance id. */
160447
+ exposureHandle() {
160448
+ return this.requireRecords().kind(hapBridgeExportsKind);
160449
+ }
160450
+ /** Load the default instance's exposure record; create it empty when none exists. */
160451
+ async loadExposure() {
160452
+ const handle = this.exposureHandle();
160453
+ const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160454
+ if (row !== null) {
160455
+ this.exposure = row.data;
160456
+ return;
160457
+ }
160458
+ await handle.put({
160459
+ id: HAP_DEFAULT_INSTANCE_ID,
160460
+ data: this.exposure
160461
+ }, { ifRev: 0 });
160462
+ }
160463
+ async writeExposure(next) {
160464
+ await this.exposureHandle().put({
160465
+ id: HAP_DEFAULT_INSTANCE_ID,
160466
+ data: next
160467
+ });
160468
+ this.exposure = next;
160469
+ }
160470
+ setExposedDevices(devices) {
160471
+ return this.writeExposure({
160472
+ ...this.exposure,
160473
+ devices
160474
+ });
160475
+ }
160476
+ setExposedActions(actions) {
160477
+ return this.writeExposure({
160478
+ ...this.exposure,
160479
+ actions
160480
+ });
160481
+ }
160482
+ /** The ports the exposure migration reads and writes through. */
160483
+ exposureMigrationPorts() {
160484
+ const handle = this.exposureHandle();
160485
+ return {
160486
+ putExposure: async (body) => {
160487
+ if (await handle.get("export-hap") !== null) return "exists";
160488
+ try {
160489
+ await handle.put({
160490
+ id: HAP_DEFAULT_INSTANCE_ID,
160491
+ data: body
160492
+ }, { ifRev: 0 });
160493
+ } catch (err) {
160494
+ if (err instanceof RevConflictError) return "exists";
160495
+ throw err;
160496
+ }
160497
+ return "created";
160498
+ },
160499
+ readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160500
+ };
160501
+ }
159019
160502
  findEntry(deviceId) {
159020
160503
  const id = String(deviceId);
159021
- return this.config.exposed.find((e) => e.deviceId === id) ?? null;
160504
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
159022
160505
  }
159023
160506
  async updateEntrySettings(deviceIdStr, settings) {
159024
- const next = this.config.exposed.map((e) => e.deviceId === deviceIdStr ? {
160507
+ const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
159025
160508
  ...e,
159026
160509
  settings
159027
160510
  } : e);
159028
- await this.updateGlobalSettings({ exposed: next });
160511
+ await this.setExposedDevices(next);
159029
160512
  }
159030
160513
  };
159031
160514
  function errMsg(err) {