@camstack/addon-export-hap 1.2.191 → 1.2.193

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.
@@ -36,8 +36,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  }) : target, mod));
37
37
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
  //#endregion
39
- let node_child_process = require("node:child_process");
40
39
  let node_crypto = require("node:crypto");
40
+ let node_child_process = require("node:child_process");
41
41
  let node_path = require("node:path");
42
42
  __toESM(node_path, 1);
43
43
  node_path = __toESM(node_path);
@@ -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-BkzQdpzF.mjs
6034
+ //#region ../types/dist/sleep-D1jjWAr8.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
@@ -6491,7 +6631,7 @@ var NOT_RUN = {
6491
6631
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6492
6632
  * because the hub (and this addon's boot) must not hang on a migration.
6493
6633
  */
6494
- async function runAddonMigrations(host, migrations, logger) {
6634
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6495
6635
  const first = migrations[0];
6496
6636
  if (first === void 0) return NOT_RUN;
6497
6637
  const owner = first.meta.owner;
@@ -6520,7 +6660,9 @@ async function runAddonMigrations(host, migrations, logger) {
6520
6660
  else if (status === "blocked") blocked.push(id);
6521
6661
  else skipped.push(id);
6522
6662
  };
6663
+ const selected = options.only === void 0 ? null : new Set(options.only);
6523
6664
  for (const step of declaration.steps) {
6665
+ if (selected !== null && !selected.has(step.id)) continue;
6524
6666
  const bound = byId.get(step.id);
6525
6667
  if (bound === void 0 || step.action === "skip") {
6526
6668
  skipped.push(step.id);
@@ -6698,11 +6840,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6698
6840
  }
6699
6841
  return out;
6700
6842
  }
6843
+ /**
6844
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6845
+ *
6846
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6847
+ * scope (global, one node, one device, one integration, one row of a business
6848
+ * collection) and the field path inside that scope — so saving the same field
6849
+ * twice updates the same ref, and the ref itself says which settings blob
6850
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6851
+ * copied onto another ref does not decrypt.
6852
+ *
6853
+ * Array items are addressed by ITEM ID, never by index
6854
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6855
+ *
6856
+ * Pure and browser-safe: no node builtins, no I/O.
6857
+ */
6858
+ /** The URI scheme of every keychain ref. */
6859
+ var SECRET_REF_SCHEME = "secret://";
6701
6860
  var GLOBAL_SCOPE = { kind: "global" };
6702
6861
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6703
6862
  function globalSecretScope() {
6704
6863
  return GLOBAL_SCOPE;
6705
6864
  }
6865
+ /**
6866
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6867
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6868
+ * addon running forked.
6869
+ */
6870
+ function normalizeSecretOwner(addonId) {
6871
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6872
+ }
6706
6873
  function encodeSegment(value) {
6707
6874
  return encodeURIComponent(value);
6708
6875
  }
@@ -6713,6 +6880,16 @@ function decodeSegment(value) {
6713
6880
  return null;
6714
6881
  }
6715
6882
  }
6883
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6884
+ function formatSecretScope(scope) {
6885
+ switch (scope.kind) {
6886
+ case "global": return "global";
6887
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6888
+ case "device": return `device/${scope.deviceId}`;
6889
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6890
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6891
+ }
6892
+ }
6716
6893
  /**
6717
6894
  * The field path of a value inside an array item, addressed by the item's id:
6718
6895
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6721,6 +6898,13 @@ function decodeSegment(value) {
6721
6898
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6722
6899
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6723
6900
  }
6901
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6902
+ function buildSecretRef(parts) {
6903
+ const owner = normalizeSecretOwner(parts.owner);
6904
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6905
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6906
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6907
+ }
6724
6908
  function parseScope(segments) {
6725
6909
  switch (segments[0]) {
6726
6910
  case "global": return {
@@ -6861,7 +7045,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6861
7045
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6862
7046
  return out;
6863
7047
  }
6864
- function rowId(row, idKey) {
7048
+ function rowId$1(row, idKey) {
6865
7049
  const raw = row[idKey];
6866
7050
  if (typeof raw === "string" && raw.length > 0) return raw;
6867
7051
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6878,7 +7062,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6878
7062
  }
6879
7063
  const storedById = /* @__PURE__ */ new Map();
6880
7064
  for (const row of storedRows) {
6881
- const id = rowId(row, node.idKey);
7065
+ const id = rowId$1(row, node.idKey);
6882
7066
  if (id !== null) storedById.set(id, row);
6883
7067
  }
6884
7068
  const kept = /* @__PURE__ */ new Set();
@@ -6888,13 +7072,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6888
7072
  rows.push(row);
6889
7073
  continue;
6890
7074
  }
6891
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7075
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6892
7076
  kept.add(id);
6893
7077
  const withId = {
6894
7078
  ...row,
6895
7079
  [node.idKey]: row[node.idKey] ?? id
6896
7080
  };
6897
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7081
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6898
7082
  const storedRow = storedById.get(id) ?? {};
6899
7083
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6900
7084
  }
@@ -7638,14 +7822,18 @@ var BaseAddon = class {
7638
7822
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7639
7823
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7640
7824
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7825
+ *
7826
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7827
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7828
+ * omitted applied ids "newer").
7641
7829
  */
7642
- async runMigrations(migrations) {
7830
+ async runMigrations(migrations, options) {
7643
7831
  const api = this.ctx.api.migrations;
7644
7832
  const report = await runAddonMigrations({
7645
7833
  declareOwner: (input) => api.declareOwner.mutate(input),
7646
7834
  startMigration: (input) => api.startMigration.mutate(input),
7647
7835
  finishMigration: (input) => api.finishMigration.mutate(input)
7648
- }, migrations, this.ctx.logger);
7836
+ }, migrations, this.ctx.logger, options);
7649
7837
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7650
7838
  return report;
7651
7839
  }
@@ -8629,6 +8817,45 @@ function normalizeAddonInitResult(result) {
8629
8817
  if (Array.isArray(result)) return { providers: result };
8630
8818
  return result;
8631
8819
  }
8820
+ var PREFIX = "records/";
8821
+ /** The base of every records failure. `detail` is the human part of the message. */
8822
+ var RecordsError = class extends Error {
8823
+ code;
8824
+ detail;
8825
+ constructor(code, detail) {
8826
+ super(`${PREFIX}${code}: ${detail}`);
8827
+ this.name = "RecordsError";
8828
+ this.code = code;
8829
+ this.detail = detail;
8830
+ }
8831
+ };
8832
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8833
+ var RevConflictError = class extends RecordsError {
8834
+ constructor(detail) {
8835
+ super("rev-conflict", detail);
8836
+ this.name = "RevConflictError";
8837
+ }
8838
+ };
8839
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8840
+ var RecordSecretUnavailableError = class extends RecordsError {
8841
+ constructor(detail) {
8842
+ super("secret-unavailable", detail);
8843
+ this.name = "RecordSecretUnavailableError";
8844
+ }
8845
+ };
8846
+ var InvalidRecordError = class extends RecordsError {
8847
+ constructor(detail) {
8848
+ super("invalid-record", detail);
8849
+ this.name = "InvalidRecordError";
8850
+ }
8851
+ };
8852
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8853
+ var DeclarationRefusedError = class extends RecordsError {
8854
+ constructor(detail) {
8855
+ super("declaration-refused", detail);
8856
+ this.name = "DeclarationRefusedError";
8857
+ }
8858
+ };
8632
8859
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8633
8860
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8634
8861
  var RECORD_DATABASES = ["settings", "events"];
@@ -8644,6 +8871,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8644
8871
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8645
8872
  var RECORD_BATCH_MAX = 1e3;
8646
8873
  var RECORD_QUERY_MAX = 1e3;
8874
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8875
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8876
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8877
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8878
+ /**
8879
+ * Secret fields of a record, addressed the way a Zod schema declares them
8880
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8881
+ * (`auth.accessToken`, `headers[].value`).
8882
+ *
8883
+ * `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
8884
+ * names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
8885
+ * key releases exactly that key's secret.
8886
+ *
8887
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8888
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8889
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8890
+ * leaf names its element: `headers[X-Api].value`.
8891
+ *
8892
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8893
+ */
8894
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8895
+ function parseSecretPath(path) {
8896
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8897
+ return path.split(".").map((raw) => {
8898
+ const each = raw.endsWith("[]");
8899
+ const map = raw.endsWith("{}");
8900
+ const key = each || map ? raw.slice(0, -2) : raw;
8901
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8902
+ return {
8903
+ key,
8904
+ each,
8905
+ map
8906
+ };
8907
+ });
8908
+ }
8909
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8910
+ function secretArrayPrefixes(path) {
8911
+ const segments = parseSecretPath(path);
8912
+ const prefixes = [];
8913
+ const walked = [];
8914
+ for (const segment of segments) {
8915
+ walked.push(segment.key);
8916
+ if (segment.each) prefixes.push(walked.join("."));
8917
+ }
8918
+ return prefixes;
8919
+ }
8920
+ function isRecord$4(value) {
8921
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8922
+ }
8923
+ function elementId(element, idKey, declared, prefix) {
8924
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8925
+ 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`);
8926
+ return id;
8927
+ }
8928
+ /**
8929
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8930
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8931
+ * result is a new body, `data` is untouched.
8932
+ */
8933
+ var REMOVE_LEAF = Symbol("remove-leaf");
8934
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8935
+ if (!isRecord$4(node)) return node;
8936
+ const segment = segments[index];
8937
+ if (segment === void 0) return node;
8938
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8939
+ const child = node[segment.key];
8940
+ const keys = [...walkedKeys, segment.key];
8941
+ const last = index === segments.length - 1;
8942
+ if (segment.each) {
8943
+ if (!Array.isArray(child)) return node;
8944
+ const prefix = keys.join(".");
8945
+ const idKey = arrayKeys[prefix];
8946
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8947
+ const mapped = child.map((element) => {
8948
+ const id = elementId(element, idKey, declared, prefix);
8949
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8950
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8951
+ });
8952
+ return {
8953
+ ...node,
8954
+ [segment.key]: mapped
8955
+ };
8956
+ }
8957
+ if (segment.map) {
8958
+ if (!isRecord$4(child)) return node;
8959
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8960
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8961
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8962
+ return [mapKey, visit({
8963
+ declared,
8964
+ concrete,
8965
+ value
8966
+ })];
8967
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8968
+ return {
8969
+ ...node,
8970
+ [segment.key]: Object.fromEntries(kept)
8971
+ };
8972
+ }
8973
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8974
+ if (last) {
8975
+ const replacement = visit({
8976
+ declared,
8977
+ concrete,
8978
+ value: child
8979
+ });
8980
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8981
+ return {
8982
+ ...node,
8983
+ [segment.key]: replacement
8984
+ };
8985
+ }
8986
+ return {
8987
+ ...node,
8988
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8989
+ };
8990
+ }
8991
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8992
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8993
+ let current = data;
8994
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8995
+ return current;
8996
+ }
8997
+ /**
8998
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8999
+ * record's refs never collide with the refs a legacy collection of the same name
9000
+ * already holds during an adoption.
9001
+ */
9002
+ function recordSecretCollection(kind) {
9003
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9004
+ }
9005
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9006
+ function recordSecretRef(owner, kind, rowId, concretePath) {
9007
+ return buildSecretRef({
9008
+ owner,
9009
+ scope: {
9010
+ kind: "row",
9011
+ collection: recordSecretCollection(kind),
9012
+ rowId
9013
+ },
9014
+ fieldPath: concretePath
9015
+ });
9016
+ }
9017
+ /**
9018
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9019
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9020
+ * token. The form hands it to the secret field, which reveals the value by ref
9021
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9022
+ * stored secret (the records door reads a view as KEEP).
9023
+ *
9024
+ * ONE implementation for the entries service and for every addon that serves
9025
+ * its own instances (`RecordIntegrationInstances`).
9026
+ */
9027
+ function isRecord$3(value) {
9028
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9029
+ }
9030
+ function secretViewsOf(owner, kind, id, decl, data) {
9031
+ if (decl.secretPaths.length === 0) return data;
9032
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9033
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9034
+ return {
9035
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9036
+ v: 1,
9037
+ set: true
9038
+ };
9039
+ });
9040
+ return isRecord$3(shown) ? shown : data;
9041
+ }
8647
9042
  /**
8648
9043
  * The share-view scope kinds a share-link token can carry. The hub mints
8649
9044
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8668,6 +9063,75 @@ var PeerBytesTicketSchema = object({
8668
9063
  */
8669
9064
  declaredBytes: number().int().nonnegative().nullable()
8670
9065
  });
9066
+ function defOf(schema) {
9067
+ const zodBag = Reflect.get(schema, "_zod");
9068
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9069
+ const def = Reflect.get(zodBag, "def");
9070
+ if (typeof def !== "object" || def === null) return {};
9071
+ return def;
9072
+ }
9073
+ function declaredHere(schema) {
9074
+ return globalRegistry.get(schema)?.secret === true;
9075
+ }
9076
+ /** Wrapper kinds whose `innerType` is the field itself. */
9077
+ var WRAPPERS = new Set([
9078
+ "optional",
9079
+ "nullable",
9080
+ "default",
9081
+ "prefault",
9082
+ "catch",
9083
+ "readonly",
9084
+ "nonoptional"
9085
+ ]);
9086
+ /**
9087
+ * The schema layers that make up ONE field: the schema itself and every
9088
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9089
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9090
+ * `.transform` on `in`).
9091
+ */
9092
+ function layersOf(schema) {
9093
+ const out = [];
9094
+ const queue = [schema];
9095
+ while (queue.length > 0) {
9096
+ const s = queue.shift();
9097
+ if (!s || out.includes(s)) continue;
9098
+ out.push(s);
9099
+ const def = defOf(s);
9100
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9101
+ if (def.type === "pipe") {
9102
+ if (def.in) queue.push(def.in);
9103
+ if (def.out) queue.push(def.out);
9104
+ }
9105
+ }
9106
+ return out;
9107
+ }
9108
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9109
+ function isZodSecret(schema) {
9110
+ return layersOf(schema).some(declaredHere);
9111
+ }
9112
+ /**
9113
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9114
+ * element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
9115
+ * map" (`applianceSecrets{}`). A declared
9116
+ * object or array is reported as one path and not descended into — everything
9117
+ * under it is secret.
9118
+ */
9119
+ function collectZodSecretPaths(schema, prefix = "") {
9120
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9121
+ const paths = [];
9122
+ for (const layer of layersOf(schema)) {
9123
+ const def = defOf(layer);
9124
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9125
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9126
+ else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
9127
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9128
+ else if (def.type === "intersection") {
9129
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9130
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9131
+ }
9132
+ }
9133
+ return [...new Set(paths)];
9134
+ }
8671
9135
  /**
8672
9136
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8673
9137
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8734,6 +9198,112 @@ var RecordKindDeclarationSchema = object({
8734
9198
  }).strict();
8735
9199
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8736
9200
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9201
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9202
+ function assertValidDeclaration(name, decl) {
9203
+ const refuse = (why) => {
9204
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9205
+ };
9206
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9207
+ const seen = /* @__PURE__ */ new Set();
9208
+ for (const index of decl.indexes) {
9209
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9210
+ seen.add(index.name);
9211
+ }
9212
+ const { retention } = decl;
9213
+ const hasSecrets = decl.secretPaths.length > 0;
9214
+ if ("ttlMs" in retention) {
9215
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9216
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9217
+ }
9218
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9219
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9220
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9221
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9222
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9223
+ 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)`);
9224
+ }
9225
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9226
+ 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`);
9227
+ }
9228
+ function bodyFieldsOf(schema) {
9229
+ return { ...toJSONSchema(schema, {
9230
+ unrepresentable: "any",
9231
+ io: "input"
9232
+ }) };
9233
+ }
9234
+ function isRecordLike(value) {
9235
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9236
+ }
9237
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9238
+ function hasNameField(json, field) {
9239
+ const branches = json["oneOf"] ?? json["anyOf"];
9240
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9241
+ const properties = json["properties"];
9242
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9243
+ }
9244
+ /**
9245
+ * Declare the kinds of a package. The keys are the kind names. The result is
9246
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9247
+ * types its handle from.
9248
+ */
9249
+ function defineRecordKinds(specs) {
9250
+ const out = {};
9251
+ for (const [name, spec] of Object.entries(specs)) {
9252
+ const secretPaths = collectZodSecretPaths(spec.schema);
9253
+ const nameField = spec.entry?.nameField ?? "name";
9254
+ const fields = bodyFieldsOf(spec.schema);
9255
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9256
+ const parsed = RecordKindDeclarationSchema.parse({
9257
+ database: spec.database,
9258
+ class: spec.class,
9259
+ writeTrigger: spec.writeTrigger,
9260
+ device: spec.device,
9261
+ at: spec.at,
9262
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9263
+ retention: spec.retention,
9264
+ deviceRemoval: spec.deviceRemoval,
9265
+ maxDataBytes: spec.maxDataBytes,
9266
+ secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
9267
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9268
+ transactFamily: spec.transactFamily,
9269
+ entry: spec.entry === void 0 ? void 0 : {
9270
+ title: spec.entry.title,
9271
+ nameField,
9272
+ fields
9273
+ }
9274
+ });
9275
+ assertValidDeclaration(name, parsed);
9276
+ out[name] = {
9277
+ name,
9278
+ schema: spec.schema,
9279
+ declaration: parsed
9280
+ };
9281
+ }
9282
+ return out;
9283
+ }
9284
+ /**
9285
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9286
+ * engine, never aged, belonging to no device.
9287
+ */
9288
+ function defineEntryKind(name, spec) {
9289
+ const defined = defineRecordKinds({ [name]: {
9290
+ schema: spec.schema,
9291
+ class: "config",
9292
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9293
+ retention: { none: "an entry goes only when the operator deletes it" },
9294
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9295
+ ...spec.database === void 0 ? {} : { database: spec.database },
9296
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9297
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9298
+ ...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
9299
+ entry: {
9300
+ title: spec.title,
9301
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9302
+ }
9303
+ } })[name];
9304
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9305
+ return defined;
9306
+ }
8737
9307
  object({
8738
9308
  field: string().min(1),
8739
9309
  on: literal("advance")
@@ -9418,6 +9988,28 @@ function toNodeId(idOrRunnerId) {
9418
9988
  const head = idOrRunnerId.split("/")[0];
9419
9989
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9420
9990
  }
9991
+ /**
9992
+ * Identity — preserves literal types for downstream inference.
9993
+ *
9994
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9995
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9996
+ * the broader unions declared on `CustomActionSpec`'s default generics.
9997
+ * Shape validity is enforced separately by the `customAction(...)` helper
9998
+ * whose return type is already a `CustomActionSpec<...>`.
9999
+ */
10000
+ function defineCustomActions(spec) {
10001
+ return spec;
10002
+ }
10003
+ function customAction(input, output, options) {
10004
+ return {
10005
+ input,
10006
+ output,
10007
+ kind: options?.kind ?? "query",
10008
+ auth: options?.auth ?? "protected",
10009
+ scope: options?.scope ?? { kind: "system" },
10010
+ ...options?.caller ? { caller: "required" } : {}
10011
+ };
10012
+ }
9421
10013
  Object.freeze({ "doorbell": "lastPressedAt" });
9422
10014
  /** Every capability name, so addon code can check a name without the schema graph. */
9423
10015
  var CAP_NAMES = Object.freeze([
@@ -11446,7 +12038,7 @@ object({
11446
12038
  params: record(string(), union([string(), number()])).optional()
11447
12039
  });
11448
12040
  //#endregion
11449
- //#region ../types/dist/composition-CRNwcFYY.mjs
12041
+ //#region ../types/dist/composition-pOHbTzRB.mjs
11450
12042
  var AUDIO_ENCODER_BY_CODEC = {
11451
12043
  opus: "libopus",
11452
12044
  aac: "aac",
@@ -13389,6 +13981,205 @@ var IntegrationInstanceRefSchema = object({
13389
13981
  ]),
13390
13982
  candidateStableId: string().optional()
13391
13983
  });
13984
+ /**
13985
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13986
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13987
+ *
13988
+ * Every instance is one record of the addon's own kind, keyed by the
13989
+ * `integrations` registry id. The records door does the secret work: a field the
13990
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13991
+ * deleting the row deletes the secret, and one row's value is never another's.
13992
+ *
13993
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13994
+ * token or the view the form was given KEEP the stored secret;
13995
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13996
+ */
13997
+ /** The most instances one addon lists (an integrations page, not a table). */
13998
+ var INSTANCES_LIST_MAX = 1e3;
13999
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
14000
+ function topLevelSecretKeys(paths) {
14001
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
14002
+ }
14003
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
14004
+ function secretMapKeys(paths) {
14005
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
14006
+ }
14007
+ /**
14008
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
14009
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
14010
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
14011
+ */
14012
+ function secretMapPatch(value) {
14013
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
14014
+ const out = {};
14015
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
14016
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
14017
+ return Object.keys(out).length > 0 ? out : null;
14018
+ }
14019
+ /** Does the kind's body schema carry an `enabled` field? */
14020
+ function declaresEnabled(kind) {
14021
+ const json = toJSONSchema(kind.schema, {
14022
+ unrepresentable: "any",
14023
+ io: "input"
14024
+ });
14025
+ const properties = Reflect.get(json, "properties");
14026
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
14027
+ }
14028
+ var RecordIntegrationInstances = class {
14029
+ records;
14030
+ kind;
14031
+ hooks;
14032
+ handle;
14033
+ secretKeys;
14034
+ secretMaps;
14035
+ nameField;
14036
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
14037
+ registryOwnsEnabled;
14038
+ constructor(records, kind, hooks) {
14039
+ this.records = records;
14040
+ this.kind = kind;
14041
+ this.hooks = hooks;
14042
+ this.handle = records.kind(kind);
14043
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
14044
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
14045
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
14046
+ this.registryOwnsEnabled = hooks.description.role === "devices";
14047
+ 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"`);
14048
+ }
14049
+ /**
14050
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
14051
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
14052
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
14053
+ */
14054
+ async readResolved(id) {
14055
+ try {
14056
+ const record = await this.handle.getResolved(id);
14057
+ return record === null ? null : {
14058
+ id,
14059
+ body: record.data,
14060
+ enabled: record.data.enabled !== false,
14061
+ secrets: "resolved"
14062
+ };
14063
+ } catch (err) {
14064
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
14065
+ const stored = await this.handle.get(id);
14066
+ if (stored === null) return null;
14067
+ return {
14068
+ id,
14069
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
14070
+ enabled: stored.data.enabled !== false,
14071
+ secrets: "unavailable"
14072
+ };
14073
+ }
14074
+ }
14075
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
14076
+ async getResolved(id) {
14077
+ return (await this.readResolved(id))?.body ?? null;
14078
+ }
14079
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
14080
+ async listResolved() {
14081
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
14082
+ const out = [];
14083
+ for (const record of page.records) {
14084
+ const read = await this.readResolved(record.id);
14085
+ if (read !== null) out.push(read);
14086
+ }
14087
+ return out;
14088
+ }
14089
+ viewOf(record) {
14090
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
14091
+ const rawName = record.data[this.nameField];
14092
+ const kind = this.hooks.kindOf?.(record.data);
14093
+ const health = this.hooks.health?.(record.data, record.id);
14094
+ return {
14095
+ id: record.id,
14096
+ name: typeof rawName === "string" ? rawName : record.id,
14097
+ configured: this.hooks.configured(record.data),
14098
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
14099
+ formValues: shown,
14100
+ ...kind !== void 0 ? { kind } : {},
14101
+ ...health?.status !== void 0 ? { status: health.status } : {},
14102
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
14103
+ };
14104
+ }
14105
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
14106
+ ...this.hooks.description,
14107
+ mintsId: true
14108
+ };
14109
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
14110
+ listInstances = async () => {
14111
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
14112
+ };
14113
+ getInstance = async ({ id }) => {
14114
+ const record = await this.handle.get(id);
14115
+ return record === null ? null : this.viewOf(record);
14116
+ };
14117
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
14118
+ createInstance = async ({ id, name, kind }) => {
14119
+ const minted = id ?? this.hooks.mintId?.({
14120
+ name,
14121
+ ...kind !== void 0 ? { kind } : {}
14122
+ });
14123
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
14124
+ await this.handle.put({
14125
+ id: minted,
14126
+ data: this.hooks.initialBody(name, kind)
14127
+ }, { ifRev: 0 });
14128
+ await this.hooks.onChanged?.(minted, "created");
14129
+ return { id: minted };
14130
+ };
14131
+ updateInstance = async ({ id, name, values }) => {
14132
+ const patch = {};
14133
+ for (const [key, value] of Object.entries(values)) {
14134
+ if (value === void 0) continue;
14135
+ if (this.secretMaps.has(key)) {
14136
+ const entries = secretMapPatch(value);
14137
+ if (entries !== null) patch[key] = entries;
14138
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
14139
+ else if (isSecretClear(value)) patch[key] = null;
14140
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
14141
+ }
14142
+ if (name !== void 0) patch[this.nameField] = name;
14143
+ await this.handle.patch(id, patch);
14144
+ await this.hooks.onChanged?.(id, "updated");
14145
+ return { ok: true };
14146
+ };
14147
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
14148
+ setInstanceEnabled = async ({ id, enabled }) => {
14149
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
14150
+ await this.handle.patch(id, { enabled });
14151
+ await this.hooks.onChanged?.(id, "enabled");
14152
+ return { ok: true };
14153
+ };
14154
+ /** The row and its keychain refs go together (the records door). */
14155
+ deleteInstance = async ({ id }) => {
14156
+ await this.handle.delete(id);
14157
+ await this.hooks.onChanged?.(id, "deleted");
14158
+ return { ok: true };
14159
+ };
14160
+ testInstance = async (input) => {
14161
+ if (this.hooks.test === void 0) return {
14162
+ success: false,
14163
+ status: "unsupported",
14164
+ error: "This integration declares no connection test"
14165
+ };
14166
+ return this.hooks.test(input);
14167
+ };
14168
+ /** The flat provider object to hand to `registerProvider`. */
14169
+ toProvider() {
14170
+ return {
14171
+ describe: this.describe,
14172
+ instanceFormSchema: this.instanceFormSchema,
14173
+ listInstances: this.listInstances,
14174
+ getInstance: this.getInstance,
14175
+ createInstance: this.createInstance,
14176
+ updateInstance: this.updateInstance,
14177
+ setInstanceEnabled: this.setInstanceEnabled,
14178
+ deleteInstance: this.deleteInstance,
14179
+ testInstance: this.testInstance
14180
+ };
14181
+ }
14182
+ };
13392
14183
  var EncodeProfileSchema = object({
13393
14184
  video: object({
13394
14185
  codec: _enum([
@@ -14504,7 +15295,13 @@ var MigrationLedgerEntrySchema = object({
14504
15295
  * joined by the engine from the catalogues it knows this boot. Absent when no
14505
15296
  * catalogue lists the id (a newer database).
14506
15297
  */
14507
- meta: MigrationMetaSchema.optional()
15298
+ meta: MigrationMetaSchema.optional(),
15299
+ /**
15300
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15301
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15302
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15303
+ */
15304
+ ownerNotLoaded: boolean().optional()
14508
15305
  });
14509
15306
  /** A catalogued migration that is not applied, with where it stands. */
14510
15307
  var MigrationPendingEntrySchema = object({
@@ -49252,6 +50049,9 @@ var RunningProposalEvidenceSchema = object({
49252
50049
  runsFound: number().int().nonnegative(),
49253
50050
  pausesFound: number().int().nonnegative(),
49254
50051
  longestPauseMs: number().nonnegative(),
50052
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50053
+ pulsesFound: number().int().nonnegative(),
50054
+ longestPulseMs: number().nonnegative(),
49255
50055
  idleFloorW: number(),
49256
50056
  noiseCeilingW: number(),
49257
50057
  plateauW: number(),
@@ -50478,13 +51278,6 @@ var ExportInstanceUnknownError = class extends Error {
50478
51278
  function statusInstanceOf(input) {
50479
51279
  return "instanceId" in input ? input.instanceId : void 0;
50480
51280
  }
50481
- /**
50482
- * A single-instance provider's check: an absent id or its own passes, any other throws
50483
- * `ExportInstanceUnknownError`.
50484
- */
50485
- function assertOwnExportInstance(addon, own, instanceId) {
50486
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
50487
- }
50488
51281
  var LinkStateSchema = _enum([
50489
51282
  "unlinked",
50490
51283
  "linked",
@@ -54336,6 +55129,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54336
55129
  }), object({ success: boolean() }), {
54337
55130
  kind: "mutation",
54338
55131
  auth: "admin"
55132
+ }), method(object({ id: string() }), object({
55133
+ rows: number().int().nonnegative(),
55134
+ secrets: number().int().nonnegative()
55135
+ }), {
55136
+ kind: "mutation",
55137
+ auth: "admin"
54339
55138
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54340
55139
  addonId: string(),
54341
55140
  settings: record(string(), unknown())
@@ -54387,6 +55186,21 @@ var IntegrationInstanceKindSchema = object({
54387
55186
  disconnectPath: string().min(1).optional()
54388
55187
  });
54389
55188
  var IntegrationInstanceDescriptionSchema = object({
55189
+ /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
55190
+ role: _enum([
55191
+ "devices",
55192
+ "services",
55193
+ "both"
55194
+ ]),
55195
+ /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
55196
+ discovery: object({
55197
+ mode: _enum([
55198
+ "none",
55199
+ "lan",
55200
+ "account"
55201
+ ]),
55202
+ scopedToInstance: boolean()
55203
+ }).optional(),
54390
55204
  /** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
54391
55205
  instanceMode: IntegrationInstanceModeSchema,
54392
55206
  /** What the instance is, for the UI (`destination`, `relay`, `account`). */
@@ -54426,10 +55240,11 @@ var IntegrationInstanceSchema = object({
54426
55240
  /** The addon's own rule (an URL is present, a client id is present...). */
54427
55241
  configured: boolean(),
54428
55242
  /**
54429
- * The instance's own on/off switch (D996): always present, derived from the record body
54430
- * (`enabled !== false`, so a row written before the field existed is on).
55243
+ * The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
55244
+ * so a row written before the field existed is on). Absent when the `integrations` registry
55245
+ * owns the switch (`describe().role` is `devices`): read it from the registry row.
54431
55246
  */
54432
- enabled: boolean(),
55247
+ enabled: boolean().optional(),
54433
55248
  /** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
54434
55249
  kind: string().optional(),
54435
55250
  /** Values for the instance form; a secret is a `SecretFieldView`, never text. */
@@ -54444,32 +55259,57 @@ var IntegrationInstancePatchSchema = object({
54444
55259
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54445
55260
  values: record(string(), unknown())
54446
55261
  });
54447
- 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({
54448
- id: IntegrationInstanceIdSchema.optional(),
54449
- name: string().min(1),
54450
- kind: string().min(1).optional()
54451
- }), object({ id: string() }), {
54452
- kind: "mutation",
54453
- auth: "admin"
54454
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54455
- kind: "mutation",
54456
- auth: "admin"
54457
- }), method(object({
54458
- id: IntegrationInstanceIdSchema,
54459
- enabled: boolean()
54460
- }), object({ ok: literal(true) }), {
54461
- kind: "mutation",
54462
- auth: "admin"
54463
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54464
- kind: "mutation",
54465
- auth: "admin"
54466
- }), optionalMethod(object({
54467
- id: IntegrationInstanceIdSchema.nullable(),
54468
- values: record(string(), unknown())
54469
- }), TestConnectionResultSchema$1, {
54470
- kind: "mutation",
54471
- auth: "admin"
54472
- });
55262
+ var integrationInstancesCapability = {
55263
+ name: "integration-instances",
55264
+ scope: "system",
55265
+ mode: "collection",
55266
+ methods: {
55267
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
55268
+ /** The form; `id: null` is the create form. */
55269
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
55270
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
55271
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
55272
+ /**
55273
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
55274
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
55275
+ */
55276
+ createInstance: method(object({
55277
+ id: IntegrationInstanceIdSchema.optional(),
55278
+ name: string().min(1),
55279
+ kind: string().min(1).optional()
55280
+ }), object({ id: string() }), {
55281
+ kind: "mutation",
55282
+ auth: "admin"
55283
+ }),
55284
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
55285
+ kind: "mutation",
55286
+ auth: "admin"
55287
+ }),
55288
+ /**
55289
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
55290
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
55291
+ */
55292
+ setInstanceEnabled: method(object({
55293
+ id: IntegrationInstanceIdSchema,
55294
+ enabled: boolean()
55295
+ }), object({ ok: literal(true) }), {
55296
+ kind: "mutation",
55297
+ auth: "admin"
55298
+ }),
55299
+ /** Delete the record and its keychain refs together. */
55300
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
55301
+ kind: "mutation",
55302
+ auth: "admin"
55303
+ }),
55304
+ testInstance: optionalMethod(object({
55305
+ id: IntegrationInstanceIdSchema.nullable(),
55306
+ values: record(string(), unknown())
55307
+ }), TestConnectionResultSchema$1, {
55308
+ kind: "mutation",
55309
+ auth: "admin"
55310
+ })
55311
+ }
55312
+ };
54473
55313
  /**
54474
55314
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54475
55315
  * session (server-initiated offer pattern, identical to the main
@@ -76394,11 +77234,15 @@ discriminatedUnion("kind", [object({
76394
77234
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
76395
77235
  * near F. A device that is not near one level most of the time has no floor.
76396
77236
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
76397
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
76398
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77237
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77238
+ * display waking): it is neither a run nor a pause. Among the remaining
77239
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77240
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77241
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77242
+ * is no run.
76399
77243
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
76400
- * grid a person would type; stop dwell covers the longest pause; start dwell
76401
- * covers the longest standby blip above T.
77244
+ * grid a person would type; stop dwell covers the longest pause and the
77245
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
76402
77246
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
76403
77247
  * run must hold exactly one true interval and nothing may flap outside.
76404
77248
  */
@@ -76409,6 +77253,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
76409
77253
  30 * SECOND_MS;
76410
77254
  60 * SECOND_MS;
76411
77255
  20 * MINUTE_MS$1;
77256
+ 90 * SECOND_MS;
77257
+ 30 * MINUTE_MS$1;
77258
+ 10 * MINUTE_MS$1;
77259
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
76412
77260
  10 * SECOND_MS;
76413
77261
  10 * SECOND_MS;
76414
77262
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80129,6 +80977,13 @@ Object.freeze({
80129
80977
  access: "create",
80130
80978
  role: "admin"
80131
80979
  },
80980
+ "integrations.clearSettings": {
80981
+ capName: "integrations",
80982
+ capScope: "system",
80983
+ addonId: null,
80984
+ access: "delete",
80985
+ role: "admin"
80986
+ },
80132
80987
  "integrations.create": {
80133
80988
  capName: "integrations",
80134
80989
  capScope: "system",
@@ -91447,6 +92302,17 @@ object({
91447
92302
  delay: number().nonnegative().optional(),
91448
92303
  commands: record(string(), unknown())
91449
92304
  });
92305
+ //#endregion
92306
+ //#region src/custom-actions.ts
92307
+ /**
92308
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92309
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92310
+ * because it unpairs every controller of the bridge.
92311
+ */
92312
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92313
+ kind: "mutation",
92314
+ auth: "admin"
92315
+ }) });
91450
92316
  process.platform, process.env["SystemRoot"];
91451
92317
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
91452
92318
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -138346,14 +139212,60 @@ function clearPairingFiles(accessoryUuid, logger) {
138346
139212
  } });
138347
139213
  }
138348
139214
  }
139215
+ //#endregion
139216
+ //#region src/hap-instance-kinds.ts
139217
+ /**
139218
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139219
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139220
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139221
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139222
+ * (`hapPersistDirOf`). The default instance is keyed by the
139223
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139224
+ * controller that paired before keeps working.
139225
+ */
139226
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139227
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139228
+ /**
139229
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139230
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139231
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139232
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139233
+ */
139234
+ function instanceSalt(instanceId) {
139235
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139236
+ }
139237
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139238
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139239
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139240
+ function hapPersistDirOf(instanceId) {
139241
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139242
+ }
139243
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139244
+ title: "HomeKit bridge",
139245
+ nameField: "name",
139246
+ schema: object({
139247
+ name: string().min(1),
139248
+ username: string().min(1),
139249
+ uuid: string().min(1),
139250
+ pincode: string().min(1).meta({ secret: true }),
139251
+ enabled: boolean().optional()
139252
+ })
139253
+ });
139254
+ function identityOfBody(body) {
139255
+ return {
139256
+ username: body.username,
139257
+ uuid: body.uuid,
139258
+ pincode: body.pincode
139259
+ };
139260
+ }
138349
139261
  /** Deterministic and distinct from every device accessory uuid. */
138350
- function actionSwitchUuid(actionId) {
138351
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139262
+ function actionSwitchUuid(actionId, instanceId) {
139263
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
138352
139264
  }
138353
139265
  function buildActionSwitch(input) {
138354
139266
  const { actionId, displayName, run } = input;
138355
139267
  const autoOffMs = input.autoOffMs ?? 1e3;
138356
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139268
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
138357
139269
  accessory.category = import_dist.Categories.SWITCH;
138358
139270
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
138359
139271
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -138427,6 +139339,10 @@ var ActionExports = class {
138427
139339
  exposedAs: e.displayName
138428
139340
  }));
138429
139341
  }
139342
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139343
+ accessoryUuids() {
139344
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139345
+ }
138430
139346
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
138431
139347
  async attachAll() {
138432
139348
  for (const entry of this.entries) try {
@@ -138494,6 +139410,7 @@ var ActionExports = class {
138494
139410
  const mapper = buildActionSwitch({
138495
139411
  actionId: entry.actionId,
138496
139412
  displayName: entry.displayName,
139413
+ instanceId: this.ports.instanceId,
138497
139414
  run: async () => {
138498
139415
  await runExportedAction(this.ports.api, this.ports.logger, {
138499
139416
  exporter: EXPORTER,
@@ -138634,6 +139551,128 @@ var BridgeHost = class {
138634
139551
  }
138635
139552
  };
138636
139553
  //#endregion
139554
+ //#region src/mappers/kind.ts
139555
+ /**
139556
+ * Which orchestrator a device gets, which device types the picker offers, and
139557
+ * what a device's HomeKit accessory is called on the wire.
139558
+ *
139559
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139560
+ * import the uuid convention without importing the registry that imports them.
139561
+ */
139562
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139563
+ /**
139564
+ * The device types the Export picker offers, and the answer to the cap's
139565
+ * `listSupportedDeviceKinds`.
139566
+ *
139567
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139568
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139569
+ * doctrine the HA exporter writes down, and the thing that confined the
139570
+ * previous exporter to cameras when it was ignored.
139571
+ *
139572
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139573
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139574
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139575
+ * absent — each needs a service whose semantics the table cannot yet honour,
139576
+ * and offering the tab before the mapping exists is how an operator gets an
139577
+ * accessory that pairs and does nothing.
139578
+ *
139579
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139580
+ * (`builders/generic/security-system.ts`), and the two things the table could
139581
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139582
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139583
+ * refuses the write out loud instead of pretending to arm.
139584
+ */
139585
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139586
+ DeviceType.Camera,
139587
+ DeviceType.Light,
139588
+ DeviceType.Switch,
139589
+ DeviceType.Siren,
139590
+ DeviceType.Sensor,
139591
+ DeviceType.Lock,
139592
+ DeviceType.Presence,
139593
+ DeviceType.AlarmPanel,
139594
+ DeviceType.Generic
139595
+ ];
139596
+ /**
139597
+ * Resolve the orchestrator for a device from its TYPE.
139598
+ *
139599
+ * `null` means "no Export tab": the picker must not offer a type no
139600
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139601
+ * to `camera` — that is what every entry persisted before this function existed
139602
+ * carries, and a transient API failure must never re-shape an exposed camera.
139603
+ */
139604
+ function pickMapperKind(deviceType) {
139605
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139606
+ if (deviceType === DeviceType.Camera) return "camera";
139607
+ const withheld = applianceExport("homekit", deviceType);
139608
+ if (withheld !== null && !withheld.exported) return null;
139609
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139610
+ }
139611
+ /**
139612
+ * The deterministic HAP accessory UUID for a device.
139613
+ *
139614
+ * One function, because three call sites depend on the answer agreeing: the
139615
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139616
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139617
+ * and the export sync state that records it.
139618
+ *
139619
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139620
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139621
+ * would make every paired camera a stranger. Generic devices get their own
139622
+ * namespace so a switch and a camera that happen to share a device id are not
139623
+ * the same HomeKit accessory.
139624
+ */
139625
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139626
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139627
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139628
+ }
139629
+ //#endregion
139630
+ //#region src/bridge-instance.ts
139631
+ var BridgeInstance = class {
139632
+ id;
139633
+ name;
139634
+ identity;
139635
+ bridgeHost;
139636
+ exposure;
139637
+ /** The devices of this bridge that have a live accessory, by device id. */
139638
+ exposed = /* @__PURE__ */ new Map();
139639
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139640
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139641
+ actionExports = null;
139642
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139643
+ syncState = /* @__PURE__ */ new Map();
139644
+ constructor(id, name, identity, bridgeHost, exposure) {
139645
+ this.id = id;
139646
+ this.name = name;
139647
+ this.identity = identity;
139648
+ this.bridgeHost = bridgeHost;
139649
+ this.exposure = exposure;
139650
+ }
139651
+ get pincode() {
139652
+ return this.identity.pincode;
139653
+ }
139654
+ findEntry(deviceId) {
139655
+ const id = String(deviceId);
139656
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139657
+ }
139658
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139659
+ accessoryUuidOf(kind, deviceId) {
139660
+ return accessoryUuidFor(kind, deviceId, this.id);
139661
+ }
139662
+ /**
139663
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139664
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139665
+ */
139666
+ pairingUuids() {
139667
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139668
+ return [
139669
+ this.identity.uuid,
139670
+ ...fromDevices,
139671
+ ...this.actionExports?.accessoryUuids() ?? []
139672
+ ];
139673
+ }
139674
+ };
139675
+ //#endregion
138637
139676
  //#region src/exposed-entry.ts
138638
139677
  /**
138639
139678
  * Carrying an exposed-device entry across a re-expose.
@@ -138671,6 +139710,83 @@ function carryForward(base, existing, keys) {
138671
139710
  return out;
138672
139711
  }
138673
139712
  //#endregion
139713
+ //#region src/hap-export-records.ts
139714
+ /**
139715
+ * What one HomeKit bridge exposes (D985, D996): a `hap-bridge-exports` row per bridge instance,
139716
+ * under the instance's own id, holds the devices it mirrors (with their per-device export
139717
+ * settings) and the actions it publishes as momentary switches. The identity a controller pairs
139718
+ * with is the sibling `hap-bridges` row; this row is what that bridge CARRIES.
139719
+ *
139720
+ * It replaces the `exposed` and `exposedActions` addon settings. The migration moved them; the
139721
+ * addon reads this record and nothing else.
139722
+ */
139723
+ var ExportDeviceSettingsSchema = object({
139724
+ multiTierService: boolean().optional(),
139725
+ streamPreference: string(),
139726
+ useBridge: boolean().optional(),
139727
+ allowTranscode: boolean().optional(),
139728
+ keepClips: boolean().optional(),
139729
+ clipRetentionDays: number().optional()
139730
+ });
139731
+ var MapperKindSchema = _enum(["camera", "generic"]);
139732
+ var ExposedConfigEntrySchema = object({
139733
+ deviceId: string(),
139734
+ displayName: string(),
139735
+ mapperKind: MapperKindSchema,
139736
+ capabilities: array(string()).optional(),
139737
+ childAccessoryUuids: array(string()).optional(),
139738
+ addedAt: number().optional(),
139739
+ settings: ExportDeviceSettingsSchema.optional()
139740
+ });
139741
+ var ActionExportEntrySchema = object({
139742
+ actionId: string(),
139743
+ displayName: string(),
139744
+ addedAt: number()
139745
+ });
139746
+ var HapBridgeExportsBodySchema = object({
139747
+ name: string().min(1),
139748
+ devices: array(ExposedConfigEntrySchema),
139749
+ actions: array(ActionExportEntrySchema)
139750
+ });
139751
+ /** The label of every exposure record: it is the instance's, not an operator's name. */
139752
+ var HAP_EXPOSURE_NAME = "HomeKit exposure";
139753
+ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139754
+ title: "HomeKit exposure",
139755
+ nameField: "name",
139756
+ schema: HapBridgeExportsBodySchema,
139757
+ writeTrigger: "an operator exposes or unexposes a device or action to HomeKit"
139758
+ });
139759
+ /** The settings keys that moved into the record; the migrations name them. */
139760
+ var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139761
+ //#endregion
139762
+ //#region src/hap-identity.ts
139763
+ /**
139764
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139765
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139766
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139767
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139768
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139769
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139770
+ *
139771
+ * Every other instance is read as it is stored; this module is only about the default one.
139772
+ */
139773
+ async function resolveDefaultBridge(ports) {
139774
+ const stored = await ports.readRecord();
139775
+ if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139776
+ if (stored.kind === "resolved") return {
139777
+ kind: "existing",
139778
+ identity: identityOfBody(stored.body)
139779
+ };
139780
+ 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");
139781
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139782
+ const body = ports.mint();
139783
+ await ports.putFresh(body);
139784
+ return {
139785
+ kind: "minted",
139786
+ identity: identityOfBody(body)
139787
+ };
139788
+ }
139789
+ //#endregion
138674
139790
  //#region src/migrations/hub-node-fields.ts
138675
139791
  /**
138676
139792
  * Fields stored once for the cluster that are facts of ONE node become node settings (D986): a
@@ -138741,40 +139857,375 @@ async function moveFixedPinToKeychain(ports) {
138741
139857
  };
138742
139858
  }
138743
139859
  //#endregion
139860
+ //#region src/migrations/exposure-to-record.ts
139861
+ /**
139862
+ * The exposure lists the addon kept in its settings (`exposed`: the devices it mirrors, with
139863
+ * their per-device settings; `exposedActions`: the actions it publishes) move into the
139864
+ * `hap-bridge-exports` record of the default instance (D985, D996). Two migrations, in order:
139865
+ *
139866
+ * 1. `moveExposureToRecord` (procedure): put the record with `ifRev: 0`, read it BACK and
139867
+ * compare it with what the settings carried; a record that does not hold the same lists
139868
+ * throws and the settings are kept. An existing record is never overwritten.
139869
+ * 2. `planDropExposureKeys` (plan): the two keys are deleted from the canonical `addon-settings`
139870
+ * rows, and only while the record holds exactly what they carry. A record that differs (the
139871
+ * operator edited the lists since) keeps the old keys, which nothing reads any more.
139872
+ *
139873
+ * An entry the schema does not know (a mapper kind the addon no longer serves) is dropped on the
139874
+ * way, which is what the boot sweep did to it anyway.
139875
+ */
139876
+ /** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
139877
+ function canonical(value) {
139878
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
139879
+ 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(",")}}`;
139880
+ return JSON.stringify(value) ?? "null";
139881
+ }
139882
+ function parsedList(value, parse) {
139883
+ if (!Array.isArray(value)) return [];
139884
+ const kept = [];
139885
+ for (const entry of value) {
139886
+ const parsed = parse(entry);
139887
+ if (parsed.success) kept.push(parsed.data);
139888
+ }
139889
+ return kept;
139890
+ }
139891
+ /** The record body the legacy settings describe. */
139892
+ function exposureBodyFrom(stored) {
139893
+ return {
139894
+ name: HAP_EXPOSURE_NAME,
139895
+ devices: parsedList(stored["exposed"], (e) => ExposedConfigEntrySchema.safeParse(e)),
139896
+ actions: parsedList(stored["exposedActions"], (e) => ActionExportEntrySchema.safeParse(e))
139897
+ };
139898
+ }
139899
+ function sameLists(a, b) {
139900
+ return canonical(a.devices) === canonical(b.devices) && canonical(a.actions) === canonical(b.actions);
139901
+ }
139902
+ async function moveExposureToRecord(ports) {
139903
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139904
+ if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
139905
+ outcome: "already-done",
139906
+ summary: { moved: false }
139907
+ };
139908
+ const body = exposureBodyFrom(stored);
139909
+ const put = await ports.putExposure(body);
139910
+ const held = await ports.readExposure();
139911
+ if (held === null) throw new Error("the HomeKit exposure record cannot be read back");
139912
+ if (put === "created" && !sameLists(held, body)) throw new Error("the HomeKit exposure record does not hold the lists it adopted");
139913
+ return put === "created" ? {
139914
+ outcome: "done",
139915
+ summary: {
139916
+ moved: true,
139917
+ devices: body.devices.length
139918
+ }
139919
+ } : {
139920
+ outcome: "already-done",
139921
+ summary: { moved: false }
139922
+ };
139923
+ }
139924
+ var rowId = (key) => `${HAP_DEFAULT_INSTANCE_ID}.${key}`;
139925
+ async function planDropExposureKeys(ports) {
139926
+ const stored = await ports.readStored(MOVED_EXPOSURE_KEYS);
139927
+ const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
139928
+ if (present.length === 0) return { edits: [] };
139929
+ const held = await ports.readExposure();
139930
+ if (held === null || !sameLists(held, exposureBodyFrom(stored))) return { edits: [] };
139931
+ return { edits: [{
139932
+ op: "deleteKeys",
139933
+ scope: ADDON_SETTINGS_TABLE,
139934
+ keys: present.map(rowId),
139935
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
139936
+ addonId: HAP_DEFAULT_INSTANCE_ID,
139937
+ key,
139938
+ value: stored[key]
139939
+ }])))
139940
+ }] };
139941
+ }
139942
+ //#endregion
139943
+ //#region src/migrations/identity-to-instance.ts
139944
+ /**
139945
+ * The bridge identity the addon kept in its settings (`identity`: username, uuid, pincode) moves
139946
+ * into the default instance record (D985, D996). Paired controllers know the bridge by exactly
139947
+ * these values, so the record is created with them UNCHANGED and the pass proves it by reading the
139948
+ * record back and comparing, field by field, before it reports `done`.
139949
+ *
139950
+ * Only once the read-back matches is the old `identity` cleared (its keychain entry released with
139951
+ * it), in this same pass: one path, no copy. An existing record is never overwritten; when it is
139952
+ * already there and names the same bridge (username, uuid) the leftover old identity of an
139953
+ * interrupted pass is cleared, and when it names another bridge the pass fails rather than guess.
139954
+ * An incomplete or unreadable legacy identity is `already-done` or throws, and never mints a new
139955
+ * one (a new identity unpairs every controller).
139956
+ */
139957
+ async function moveIdentityToDefaultInstance(ports) {
139958
+ const legacy = await ports.readLegacyIdentity();
139959
+ if (legacy === null) return {
139960
+ outcome: "already-done",
139961
+ summary: { moved: false }
139962
+ };
139963
+ const name = (await ports.readBridgeName()).trim();
139964
+ const body = {
139965
+ name: name.length > 0 ? name : "CamStack Bridge",
139966
+ username: legacy.username,
139967
+ uuid: legacy.uuid,
139968
+ pincode: legacy.pincode
139969
+ };
139970
+ const put = await ports.putDefaultRecord(body);
139971
+ const held = await ports.readDefaultRecord();
139972
+ if (held === null) throw new Error("the HomeKit default instance record cannot be read back");
139973
+ if (put === "exists") {
139974
+ if (held.username !== body.username || held.uuid !== body.uuid) throw new Error("the HomeKit default instance is another bridge than the stored identity");
139975
+ await ports.clearLegacyIdentity();
139976
+ return {
139977
+ outcome: "done",
139978
+ summary: {
139979
+ moved: false,
139980
+ cleared: true
139981
+ }
139982
+ };
139983
+ }
139984
+ if (!sameIdentity(identityOfBody(held), identityOfBody(body))) throw new Error("the HomeKit default instance does not hold the identity it adopted");
139985
+ await ports.clearLegacyIdentity();
139986
+ return {
139987
+ outcome: "done",
139988
+ summary: { moved: true }
139989
+ };
139990
+ }
139991
+ function sameIdentity(a, b) {
139992
+ return a.username === b.username && a.uuid === b.uuid && a.pincode === b.pincode;
139993
+ }
139994
+ /**
139995
+ * The identity a settings value describes, secrets resolved; null when it is not a complete
139996
+ * identity (first boot, or the empty sentinel). A pincode still a keychain marker was not
139997
+ * resolved: that throws, because treating "unreadable" as "absent" would mint a new identity.
139998
+ */
139999
+ function legacyIdentityOf(value) {
140000
+ if (typeof value !== "object" || value === null) return null;
140001
+ const username = Reflect.get(value, "username");
140002
+ const uuid = Reflect.get(value, "uuid");
140003
+ const pincode = Reflect.get(value, "pincode");
140004
+ if (isSecretMarker(pincode)) throw new Error("the stored HomeKit setup code cannot be resolved");
140005
+ if (typeof username !== "string" || typeof uuid !== "string" || typeof pincode !== "string" || username === "" || uuid === "" || pincode === "") return null;
140006
+ return {
140007
+ username,
140008
+ uuid,
140009
+ pincode
140010
+ };
140011
+ }
140012
+ //#endregion
140013
+ //#region src/migrations/bridge-name-to-instance.ts
140014
+ async function moveBridgeNameToInstance(ports) {
140015
+ const name = (await ports.readBridgeName()).trim();
140016
+ if (name === "") return {
140017
+ outcome: "already-done",
140018
+ summary: { renamed: false }
140019
+ };
140020
+ const held = await ports.readDefaultRecord();
140021
+ if (held === null || held.name === name) return {
140022
+ outcome: "already-done",
140023
+ summary: { renamed: false }
140024
+ };
140025
+ await ports.patchDefaultName(name);
140026
+ const after = await ports.readDefaultRecord();
140027
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140028
+ return {
140029
+ outcome: "done",
140030
+ summary: { renamed: true }
140031
+ };
140032
+ }
140033
+ //#endregion
140034
+ //#region src/migrations/drop-global-knobs.ts
140035
+ /**
140036
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140037
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140038
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140039
+ * fact of one node, which the node row carries since the per-node migration.
140040
+ *
140041
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140042
+ * keychain value would be orphaned otherwise):
140043
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140044
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140045
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140046
+ * can never lose the value. A `@<nodeId>` row is never touched.
140047
+ */
140048
+ async function clearFixedPin(ports) {
140049
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140050
+ outcome: "already-done",
140051
+ summary: { cleared: false }
140052
+ };
140053
+ await ports.clearFixedPin();
140054
+ return {
140055
+ outcome: "done",
140056
+ summary: { cleared: true }
140057
+ };
140058
+ }
140059
+ async function planDropGlobalKnobRows(addonId, ports) {
140060
+ const stored = await ports.readStored([
140061
+ "bridgeName",
140062
+ "fixedPin",
140063
+ "interfaceName",
140064
+ nodeKeyOf("interfaceName")
140065
+ ]);
140066
+ const present = [
140067
+ "bridgeName",
140068
+ "fixedPin",
140069
+ "interfaceName"
140070
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140071
+ if (present.length === 0) return { edits: [] };
140072
+ const rowId = (key) => `${addonId}.${key}`;
140073
+ return { edits: [{
140074
+ op: "deleteKeys",
140075
+ scope: ADDON_SETTINGS_TABLE,
140076
+ keys: present.map(rowId),
140077
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140078
+ addonId,
140079
+ key,
140080
+ value: stored[key]
140081
+ }])))
140082
+ }] };
140083
+ }
140084
+ //#endregion
138744
140085
  //#region src/migrations/index.ts
138745
140086
  var EXPORT_HAP_ID = "export-hap";
140087
+ var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
140088
+ var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
140089
+ var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
140090
+ var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140091
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140092
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140093
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
138746
140094
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
138747
- var ADDON_MIGRATIONS = [{
138748
- meta: {
138749
- id: "export-hap/2026-11-03-interface-name-per-node",
138750
- owner: EXPORT_HAP_ID,
138751
- level: "addon-state",
138752
- seq: 1,
138753
- dependsOn: [],
138754
- store: "settings",
138755
- scope: "per-node",
138756
- onFailure: "tolerate",
138757
- bodyKind: "plan",
138758
- description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
138759
- fixtureMark: "the bridge name the migration does not know"
138760
- },
138761
- plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
138762
- }, {
138763
- meta: {
138764
- id: "export-hap/2026-11-03-fixed-pin-to-keychain",
138765
- owner: EXPORT_HAP_ID,
138766
- level: "addon-state",
138767
- seq: 2,
138768
- dependsOn: [],
138769
- store: "settings",
138770
- scope: "cluster",
138771
- onFailure: "tolerate",
138772
- bodyKind: "procedure",
138773
- description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
138774
- fixtureMark: "the bridge name the migration does not know"
138775
- },
138776
- procedure: moveFixedPinToKeychain
138777
- }];
140095
+ var ADDON_MIGRATIONS = [
140096
+ {
140097
+ meta: {
140098
+ id: INTERFACE_NAME_PER_NODE_ID,
140099
+ owner: EXPORT_HAP_ID,
140100
+ level: "addon-state",
140101
+ seq: 1,
140102
+ dependsOn: [],
140103
+ store: "settings",
140104
+ scope: "per-node",
140105
+ onFailure: "tolerate",
140106
+ bodyKind: "plan",
140107
+ description: "Copy the bare network interface setting to its hub node row; the bare row stays for a release",
140108
+ fixtureMark: "the bridge name the migration does not know"
140109
+ },
140110
+ plan: (ports) => planHubNodeFields(EXPORT_HAP_ID, ["interfaceName"], ports)
140111
+ },
140112
+ {
140113
+ meta: {
140114
+ id: FIXED_PIN_TO_KEYCHAIN_ID,
140115
+ owner: EXPORT_HAP_ID,
140116
+ level: "addon-state",
140117
+ seq: 2,
140118
+ dependsOn: [],
140119
+ store: "settings",
140120
+ scope: "cluster",
140121
+ onFailure: "tolerate",
140122
+ bodyKind: "procedure",
140123
+ description: "Move the fixed setup code from an inline setting into the keychain, where a password field keeps it",
140124
+ fixtureMark: "the bridge name the migration does not know"
140125
+ },
140126
+ procedure: moveFixedPinToKeychain
140127
+ },
140128
+ {
140129
+ meta: {
140130
+ id: IDENTITY_TO_INSTANCE_ID,
140131
+ owner: EXPORT_HAP_ID,
140132
+ level: "addon-state",
140133
+ seq: 3,
140134
+ dependsOn: [],
140135
+ store: "settings",
140136
+ scope: "cluster",
140137
+ onFailure: "block-owner",
140138
+ bodyKind: "procedure",
140139
+ 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",
140140
+ fixtureMark: "the bridge name the migration does not know"
140141
+ },
140142
+ procedure: moveIdentityToDefaultInstance
140143
+ },
140144
+ {
140145
+ meta: {
140146
+ id: EXPOSURE_TO_RECORD_ID,
140147
+ owner: EXPORT_HAP_ID,
140148
+ level: "addon-state",
140149
+ seq: 4,
140150
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140151
+ store: "settings",
140152
+ scope: "cluster",
140153
+ onFailure: "block-owner",
140154
+ bodyKind: "procedure",
140155
+ description: "Move the exposed devices and actions into the default bridge exposure record, verified by read-back",
140156
+ fixtureMark: "the bridge name the migration does not know"
140157
+ },
140158
+ procedure: moveExposureToRecord
140159
+ },
140160
+ {
140161
+ meta: {
140162
+ id: DROP_EXPOSURE_KEYS_ID,
140163
+ owner: EXPORT_HAP_ID,
140164
+ level: "addon-state",
140165
+ seq: 5,
140166
+ dependsOn: [EXPOSURE_TO_RECORD_ID],
140167
+ store: "settings",
140168
+ scope: "cluster",
140169
+ onFailure: "tolerate",
140170
+ bodyKind: "plan",
140171
+ description: "Delete the old exposed and exposedActions settings once the record holds exactly what they carried",
140172
+ fixtureMark: "the bridge name the migration does not know"
140173
+ },
140174
+ plan: planDropExposureKeys
140175
+ },
140176
+ {
140177
+ meta: {
140178
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140179
+ owner: EXPORT_HAP_ID,
140180
+ level: "addon-state",
140181
+ seq: 6,
140182
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140183
+ store: "settings",
140184
+ scope: "cluster",
140185
+ onFailure: "block-owner",
140186
+ bodyKind: "procedure",
140187
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140188
+ fixtureMark: "the bridge name the migration does not know"
140189
+ },
140190
+ procedure: moveBridgeNameToInstance
140191
+ },
140192
+ {
140193
+ meta: {
140194
+ id: DROP_GLOBAL_KNOBS_ID,
140195
+ owner: EXPORT_HAP_ID,
140196
+ level: "addon-state",
140197
+ seq: 7,
140198
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140199
+ store: "settings",
140200
+ scope: "cluster",
140201
+ onFailure: "tolerate",
140202
+ bodyKind: "procedure",
140203
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140204
+ fixtureMark: "the bridge name the migration does not know"
140205
+ },
140206
+ procedure: clearFixedPin
140207
+ },
140208
+ {
140209
+ meta: {
140210
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140211
+ owner: EXPORT_HAP_ID,
140212
+ level: "addon-state",
140213
+ seq: 8,
140214
+ dependsOn: [
140215
+ BRIDGE_NAME_TO_INSTANCE_ID,
140216
+ DROP_GLOBAL_KNOBS_ID,
140217
+ INTERFACE_NAME_PER_NODE_ID
140218
+ ],
140219
+ store: "settings",
140220
+ scope: "cluster",
140221
+ onFailure: "tolerate",
140222
+ bodyKind: "plan",
140223
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140224
+ fixtureMark: "the bridge name the migration does not know"
140225
+ },
140226
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
140227
+ }
140228
+ ];
138778
140229
  //#endregion
138779
140230
  //#region src/hap-setup-uri.ts
138780
140231
  function errMsg$15(e) {
@@ -156867,81 +158318,6 @@ function errMsg$3(err) {
156867
158318
  return err instanceof Error ? err.message : String(err);
156868
158319
  }
156869
158320
  //#endregion
156870
- //#region src/mappers/kind.ts
156871
- /**
156872
- * Which orchestrator a device gets, which device types the picker offers, and
156873
- * what a device's HomeKit accessory is called on the wire.
156874
- *
156875
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
156876
- * import the uuid convention without importing the registry that imports them.
156877
- */
156878
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
156879
- /**
156880
- * The device types the Export picker offers, and the answer to the cap's
156881
- * `listSupportedDeviceKinds`.
156882
- *
156883
- * A UI FILTER, nothing more. Whether a device actually exports anything is
156884
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
156885
- * doctrine the HA exporter writes down, and the thing that confined the
156886
- * previous exporter to cameras when it was ignored.
156887
- *
156888
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
156889
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
156890
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
156891
- * absent — each needs a service whose semantics the table cannot yet honour,
156892
- * and offering the tab before the mapping exists is how an operator gets an
156893
- * accessory that pairs and does nothing.
156894
- *
156895
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
156896
- * (`builders/generic/security-system.ts`), and the two things the table could
156897
- * not previously honour are now honoured explicitly: HomeKit is only ever
156898
- * offered the arm modes the panel accepts, and a panel that requires a PIN
156899
- * refuses the write out loud instead of pretending to arm.
156900
- */
156901
- var HAP_EXPORTABLE_DEVICE_TYPES = [
156902
- DeviceType.Camera,
156903
- DeviceType.Light,
156904
- DeviceType.Switch,
156905
- DeviceType.Siren,
156906
- DeviceType.Sensor,
156907
- DeviceType.Lock,
156908
- DeviceType.Presence,
156909
- DeviceType.AlarmPanel,
156910
- DeviceType.Generic
156911
- ];
156912
- /**
156913
- * Resolve the orchestrator for a device from its TYPE.
156914
- *
156915
- * `null` means "no Export tab": the picker must not offer a type no
156916
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
156917
- * to `camera` — that is what every entry persisted before this function existed
156918
- * carries, and a transient API failure must never re-shape an exposed camera.
156919
- */
156920
- function pickMapperKind(deviceType) {
156921
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
156922
- if (deviceType === DeviceType.Camera) return "camera";
156923
- const withheld = applianceExport("homekit", deviceType);
156924
- if (withheld !== null && !withheld.exported) return null;
156925
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
156926
- }
156927
- /**
156928
- * The deterministic HAP accessory UUID for a device.
156929
- *
156930
- * One function, because three call sites depend on the answer agreeing: the
156931
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
156932
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
156933
- * and the export sync state that records it.
156934
- *
156935
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
156936
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
156937
- * would make every paired camera a stranger. Generic devices get their own
156938
- * namespace so a switch and a camera that happen to share a device id are not
156939
- * the same HomeKit accessory.
156940
- */
156941
- function accessoryUuidFor(kind, deviceId) {
156942
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
156943
- }
156944
- //#endregion
156945
158321
  //#region src/multi-tier/rtp-streaming-control.ts
156946
158322
  /**
156947
158323
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -157744,7 +159120,7 @@ async function buildCameraAccessory(input) {
157744
159120
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
157745
159121
  const isDoorbell = capNames.has("doorbell");
157746
159122
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
157747
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159123
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
157748
159124
  accessory.category = category;
157749
159125
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
157750
159126
  const bctx = {
@@ -157879,7 +159255,7 @@ async function buildGenericAccessory(input) {
157879
159255
  const rows = rowsForCaps(capNames);
157880
159256
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
157881
159257
  const deviceType = await resolveDeviceType(proxy);
157882
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159258
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
157883
159259
  accessory.category = accessoryCategoryFor(deviceType);
157884
159260
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
157885
159261
  const bctx = {
@@ -157977,9 +159353,8 @@ function syncStateToJson(map) {
157977
159353
  * Operator flow:
157978
159354
  * 1. Install + enable the addon (hub-only, group `export-hap`).
157979
159355
  * 2. On first boot the addon generates a random pincode + bridge
157980
- * MAC username and persists them on `this.config.identity` via
157981
- * `updateGlobalSettings` (no JSON sidecar files — the kernel
157982
- * addon-store IS the cache).
159356
+ * MAC username and persists them in the default instance record
159357
+ * (`hap-bridges`, no JSON sidecar files).
157983
159358
  * 3. The setup URI (`X-HM://…`) is logged AND surfaced via the
157984
159359
  * `getStatus` cap method so the wizard UI can render the QR.
157985
159360
  * 4. Operator opens iOS Home → + → scan QR → enter pincode.
@@ -158113,17 +159488,8 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
158113
159488
  }
158114
159489
  ];
158115
159490
  var DEFAULT_CONFIG = {
158116
- bridgeName: "CamStack Bridge",
158117
- fixedPin: "",
158118
159491
  interfaceName: "",
158119
159492
  clipRetentionDays: 14,
158120
- identity: {
158121
- username: "",
158122
- pincode: "",
158123
- uuid: ""
158124
- },
158125
- exposed: [],
158126
- exposedActions: [],
158127
159493
  exportSyncState: {}
158128
159494
  };
158129
159495
  var BANNED_PINCODES = new Set([
@@ -158140,10 +159506,6 @@ var BANNED_PINCODES = new Set([
158140
159506
  "123-45-678",
158141
159507
  "876-54-321"
158142
159508
  ]);
158143
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
158144
- function isValidPincode(pin) {
158145
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
158146
- }
158147
159509
  function generateUsername() {
158148
159510
  const bytes = (0, node_crypto.randomBytes)(6);
158149
159511
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -158158,18 +159520,23 @@ function generatePincode() {
158158
159520
  }
158159
159521
  throw new Error("export-hap: failed to generate a non-trivial pincode");
158160
159522
  }
159523
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
158161
159524
  function buildBridgeUuid(bridgeName) {
158162
159525
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
158163
159526
  }
158164
159527
  var ExportHapAddon = class extends BaseAddon {
158165
- /** The bridge setup code pairs a controller: a credential, kept in the keychain (D787). */
158166
- secretStatePaths = ["identity.pincode"];
158167
- exposed = /* @__PURE__ */ new Map();
158168
- /** The exported actions — switches beside the devices (D968). */
158169
- actionExports = null;
159528
+ /**
159529
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159530
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159531
+ */
159532
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159533
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159534
+ bridges = /* @__PURE__ */ new Map();
159535
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159536
+ lifecycle = Promise.resolve();
158170
159537
  lastError;
158171
- /** Shared HAP setup code applied to every published accessory. */
158172
- pincode = "";
159538
+ /** The HomeKit instances (D985): one record per bridge identity. */
159539
+ instances = null;
158173
159540
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
158174
159541
  bind;
158175
159542
  /**
@@ -158213,29 +159580,39 @@ var ExportHapAddon = class extends BaseAddon {
158213
159580
  hksvBuilds = new HksvBuildOutcomes();
158214
159581
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
158215
159582
  hksvClipPlanes = null;
158216
- /**
158217
- * THE bridge. Lazily created and published the first time a non-camera
158218
- * accessory needs it; never torn down while the addon runs, because an
158219
- * unpublish would drop a pairing the operator already entered a code for.
158220
- */
158221
- bridgeHost = null;
158222
159583
  constructor() {
158223
159584
  super({ ...DEFAULT_CONFIG });
158224
159585
  }
158225
159586
  async onInitialize() {
159587
+ const records = this.ctx.records;
159588
+ if (records === void 0) throw new Error("export-hap needs ctx.records — check execution.placement (hub-only)");
159589
+ await records.declare({
159590
+ "hap-bridges": hapBridgesKind,
159591
+ "hap-bridge-exports": hapBridgeExportsKind
159592
+ });
159593
+ this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159594
+ description: {
159595
+ role: "services",
159596
+ instanceMode: "multiple",
159597
+ kind: "bridge",
159598
+ canTest: false
159599
+ },
159600
+ formSchema: (id) => this.bridgeForm(id),
159601
+ initialBody: (name) => ({
159602
+ name,
159603
+ username: generateUsername(),
159604
+ uuid: buildBridgeUuid(name),
159605
+ pincode: generatePincode()
159606
+ }),
159607
+ mintId: () => `hap-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
159608
+ configured: (body) => body.username !== "" && body.pincode !== "",
159609
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159610
+ });
158226
159611
  await this.migrateSettings();
158227
- const identity = await this.ensureIdentity();
158228
- this.pincode = identity.pincode;
159612
+ await this.ensureDefaultBridge();
158229
159613
  this.bind = this.config.interfaceName || void 0;
158230
- this.bridgeHost = new BridgeHost({
158231
- displayName: this.config.bridgeName,
158232
- uuid: identity.uuid,
158233
- pincode: identity.pincode,
158234
- bind: this.bind,
158235
- logger: this.ctx.logger
158236
- });
158237
159614
  try {
158238
- await initHapStorage(node_path.join(this.ctx.dataDir, "hap-store"));
159615
+ await initHapStorage(node_path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
158239
159616
  } catch (err) {
158240
159617
  this.lastError = errMsg(err);
158241
159618
  this.ctx.logger.error("export-hap: HAP storage init failed", { meta: { error: this.lastError } });
@@ -158247,7 +159624,7 @@ var ExportHapAddon = class extends BaseAddon {
158247
159624
  this.hksvClipStore = new HksvClipStore({
158248
159625
  logger: this.ctx.logger.child("hksv-clips"),
158249
159626
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
158250
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159627
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
158251
159628
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
158252
159629
  resolveFfmpeg: this.pinnedFfmpeg,
158253
159630
  spawnFn: node_child_process.spawn,
@@ -158260,187 +159637,391 @@ var ExportHapAddon = class extends BaseAddon {
158260
159637
  }) })
158261
159638
  });
158262
159639
  await this.serveHksvClipPlanes();
159640
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159641
+ for (const row of ordered) try {
159642
+ await this.startInstance(row.id);
159643
+ } catch (err) {
159644
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159645
+ instanceId: row.id,
159646
+ error: errMsg(err)
159647
+ } });
159648
+ }
159649
+ this.ctx.addDisposer(async () => {
159650
+ await this.enqueue(async () => {
159651
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159652
+ });
159653
+ });
159654
+ this.subscribeDeviceProvisionedForReconcile();
159655
+ this.subscribeDeviceReadyForReconcile();
159656
+ this.subscribeStorageLocationsForClips();
159657
+ const provider = this.buildExportProvider();
159658
+ const clipsProvider = createHksvVideoclipsProvider({
159659
+ logger: this.ctx.logger.child("hksv-clips"),
159660
+ addonId: EXPORT_HAP_ADDON_ID,
159661
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159662
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159663
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159664
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159665
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159666
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159667
+ });
159668
+ return {
159669
+ providers: [
159670
+ {
159671
+ capability: deviceExportCapability,
159672
+ provider
159673
+ },
159674
+ {
159675
+ capability: videoclipsCapability,
159676
+ provider: clipsProvider
159677
+ },
159678
+ {
159679
+ capability: integrationInstancesCapability,
159680
+ provider: this.requireInstances().toProvider()
159681
+ }
159682
+ ],
159683
+ customActions: exportHapActions,
159684
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159685
+ };
159686
+ }
159687
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159688
+ enqueue(job) {
159689
+ const run = this.lifecycle.then(job);
159690
+ this.lifecycle = run.then(() => void 0, () => void 0);
159691
+ return run;
159692
+ }
159693
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159694
+ instanceForDevice(deviceId) {
159695
+ const key = String(deviceId);
159696
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159697
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159698
+ }
159699
+ requireBridge(instanceId) {
159700
+ const inst = this.bridges.get(instanceId);
159701
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159702
+ return inst;
159703
+ }
159704
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159705
+ async startInstance(id) {
159706
+ await this.stopInstance(id);
159707
+ const resolved = await this.requireInstances().readResolved(id);
159708
+ if (resolved === null || !resolved.enabled) return;
159709
+ if (resolved.secrets === "unavailable") {
159710
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159711
+ return;
159712
+ }
159713
+ const identity = identityOfBody(resolved.body);
159714
+ const exposure = await this.loadExposure(id);
159715
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159716
+ displayName: resolved.body.name,
159717
+ uuid: identity.uuid,
159718
+ pincode: identity.pincode,
159719
+ bind: this.bind,
159720
+ logger: this.ctx.logger
159721
+ }), exposure);
159722
+ this.bridges.set(id, inst);
159723
+ this.warnOnDuplicateName(inst);
158263
159724
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
158264
- const cleaned = this.config.exposed.filter((entry) => {
159725
+ const cleaned = inst.exposure.devices.filter((entry) => {
158265
159726
  if (validKinds.has(entry.mapperKind)) return true;
158266
159727
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
158267
159728
  return false;
158268
159729
  });
158269
- if (cleaned.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: cleaned });
159730
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
158270
159731
  for (const entry of cleaned) {
158271
159732
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
158272
159733
  try {
158273
- await this.attachMapper(entry);
159734
+ await this.attachMapper(inst, entry);
158274
159735
  const numericId = Number.parseInt(entry.deviceId, 10);
158275
159736
  if (Number.isFinite(numericId)) {
158276
- const fp = await this.computeExportFingerprint(numericId);
158277
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159737
+ const fp = await this.computeExportFingerprint(inst, numericId);
159738
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
158278
159739
  }
158279
159740
  } catch (err) {
158280
159741
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
158281
159742
  }
158282
159743
  }
158283
- this.actionExports = new ActionExports({
159744
+ inst.actionExports = new ActionExports({
158284
159745
  api: this.ctx.api,
158285
159746
  logger: this.ctx.logger,
159747
+ instanceId: id,
158286
159748
  publish: async (accessory) => {
158287
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159749
+ if (await inst.bridgeHost.add(accessory)) return;
158288
159750
  await publishStandalone(accessory, {
158289
- pincode: this.pincode,
159751
+ pincode: inst.pincode,
158290
159752
  port: 0,
158291
159753
  bind: this.bind,
158292
159754
  logger: this.ctx.logger
158293
159755
  });
158294
159756
  },
158295
159757
  unpublish: async (accessory) => {
158296
- if (this.bridgeHost?.holds(accessory) === true) {
158297
- this.bridgeHost.remove(accessory);
159758
+ if (inst.bridgeHost.holds(accessory)) {
159759
+ inst.bridgeHost.remove(accessory);
158298
159760
  return;
158299
159761
  }
158300
159762
  await unpublishAccessory(accessory, this.ctx.logger);
158301
159763
  },
158302
- persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
158303
- }, this.config.exposedActions ?? []);
158304
- await this.actionExports.attachAll();
158305
- await this.actionExports.reconcile();
158306
- this.ctx.addDisposer(async () => {
158307
- await this.actionExports?.dispose();
158308
- await this.detachAll();
158309
- await this.bridgeHost?.dispose();
159764
+ persist: (entries) => this.setExposedActions(inst, entries)
159765
+ }, inst.exposure.actions);
159766
+ await inst.actionExports.attachAll();
159767
+ await inst.actionExports.reconcile();
159768
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159769
+ instanceId: id,
159770
+ name: inst.name,
159771
+ devices: inst.exposed.size
159772
+ } });
159773
+ }
159774
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159775
+ async stopInstance(id) {
159776
+ const inst = this.bridges.get(id);
159777
+ if (inst === void 0) return;
159778
+ this.bridges.delete(id);
159779
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159780
+ inst.pendingRebuildTimers.clear();
159781
+ await inst.actionExports?.dispose();
159782
+ await this.detachAll(inst);
159783
+ await inst.bridgeHost.dispose();
159784
+ }
159785
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159786
+ async applyChange(id, change) {
159787
+ if (change === "deleted") {
159788
+ await this.removeInstance(id);
159789
+ return;
159790
+ }
159791
+ const resolved = await this.requireInstances().readResolved(id);
159792
+ if (resolved === null || !resolved.enabled) {
159793
+ await this.stopInstance(id);
159794
+ return;
159795
+ }
159796
+ const running = this.bridges.get(id);
159797
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159798
+ const next = identityOfBody(resolved.body);
159799
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159800
+ }
159801
+ await this.startInstance(id);
159802
+ }
159803
+ /**
159804
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159805
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159806
+ */
159807
+ async removeInstance(id) {
159808
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159809
+ await this.stopInstance(id);
159810
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159811
+ await this.exposureHandle().delete(id);
159812
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159813
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159814
+ }
159815
+ /**
159816
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159817
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159818
+ * devices stay.
159819
+ */
159820
+ regenerateBridge(instanceId) {
159821
+ return this.enqueue(async () => {
159822
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159823
+ await this.stopInstance(instanceId);
159824
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159825
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159826
+ await this.startInstance(instanceId);
159827
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159828
+ instanceId,
159829
+ accessories: uuids.length
159830
+ } });
159831
+ return { regenerated: true };
158310
159832
  });
158311
- this.subscribeDeviceProvisionedForReconcile();
158312
- this.subscribeDeviceReadyForReconcile();
158313
- this.subscribeStorageLocationsForClips();
158314
- this.disposeSharedRebuildTimers();
158315
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
158316
- const provider = {
158317
- getStatus: async (input) => {
158318
- ownInstance(statusInstanceOf(input));
158319
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
158320
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
158321
- const setup = this.buildSetupBlock();
158322
- return {
158323
- linkState,
158324
- exposedDeviceCount: this.exposed.size,
158325
- ...this.lastError ? { error: this.lastError } : {},
158326
- ...setup ? { setup } : {}
158327
- };
158328
- },
158329
- listInstances: async () => [{
158330
- instanceId: EXPORT_HAP_ADDON_ID,
158331
- name: "HomeKit",
158332
- enabled: true,
159833
+ }
159834
+ warnOnDuplicateName(inst) {
159835
+ const key = inst.name.trim().toLowerCase();
159836
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159837
+ if (others.length === 0) return;
159838
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159839
+ instanceId: inst.id,
159840
+ name: inst.name,
159841
+ others: others.map((b) => b.id)
159842
+ } });
159843
+ }
159844
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159845
+ bridgeForm(id) {
159846
+ const inst = id === null ? void 0 : this.bridges.get(id);
159847
+ let qr = "";
159848
+ try {
159849
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159850
+ } catch (err) {
159851
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159852
+ instanceId: id,
159853
+ error: errMsg(err)
159854
+ } });
159855
+ }
159856
+ return this.schema({ sections: [{
159857
+ id: "bridge",
159858
+ title: "HomeKit bridge",
159859
+ description: "One HomeKit bridge carries every exported device that is not a camera (switches, sensors, locks, alarm panels); each camera is published as its own accessory with the same setup code. In iOS Home tap + → Add Accessory and enter the setup code.",
159860
+ fields: [...inst === void 0 ? [] : [{
159861
+ type: "info",
159862
+ key: "setupCode",
159863
+ label: "Setup code",
159864
+ content: inst.pincode
159865
+ }, ...qr === "" ? [] : [{
159866
+ type: "qr-code",
159867
+ key: "setupQr",
159868
+ label: "Pairing QR",
159869
+ caption: "Scan with the iOS Camera app.",
159870
+ value: qr,
159871
+ size: 192
159872
+ }]], ...id === null ? [] : [{
159873
+ type: "addon-action-button",
159874
+ key: "__regenerate-bridge",
159875
+ label: "Regenerate setup code",
159876
+ description: "Creates a new setup code and unpairs every controller from this bridge: each iPhone, iPad and Apple TV must add it again. The bridge and its exported devices stay.",
159877
+ addonId: EXPORT_HAP_ADDON_ID,
159878
+ action: "regenerateBridge",
159879
+ buttonLabel: "Regenerate",
159880
+ variant: "danger",
159881
+ paramsStatic: { instanceId: id },
159882
+ confirmMessage: "Regenerate the setup code? Every controller paired with this bridge is unpaired, its pairings are cleared and the bridge is republished. You must pair each one again with the new code."
159883
+ }]]
159884
+ }] });
159885
+ }
159886
+ /** Whole-addon status of the bridges: linked when any is paired. */
159887
+ statusOf(bridges) {
159888
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
159889
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159890
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
159891
+ return {
159892
+ linkState,
159893
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
159894
+ ...this.lastError ? { error: this.lastError } : {},
159895
+ ...setup ? { setup } : {}
159896
+ };
159897
+ }
159898
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
159899
+ bridgesOf(instanceId) {
159900
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
159901
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159902
+ }
159903
+ buildExportProvider() {
159904
+ return {
159905
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
159906
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
159907
+ instanceId: row.id,
159908
+ name: row.body.name,
159909
+ enabled: row.enabled,
158333
159910
  kind: "hap-bridge"
158334
- }],
159911
+ })),
158335
159912
  listSupportedDeviceKinds: async ({ instanceId }) => {
158336
- ownInstance(instanceId);
159913
+ this.bridgesOf(instanceId);
158337
159914
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
158338
159915
  },
158339
- listExposedDevices: async ({ instanceId }) => {
158340
- ownInstance(instanceId);
158341
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
158342
- const entry = this.config.exposed.find((e) => e.deviceId === deviceId);
158343
- return {
158344
- deviceId,
158345
- exposedAs: m.accessory.displayName,
158346
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
158347
- };
158348
- });
158349
- },
158350
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
158351
- ownInstance(instanceId);
158352
- return this.exposeDevice(deviceId, capabilities);
158353
- },
158354
- unexposeDevice: async ({ instanceId, deviceId }) => {
158355
- ownInstance(instanceId);
158356
- return this.unexposeDevice(deviceId);
158357
- },
159916
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
159917
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159918
+ return {
159919
+ deviceId,
159920
+ exposedAs: m.accessory.displayName,
159921
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159922
+ };
159923
+ })),
159924
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
159925
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
158358
159926
  listSupportedEntityKinds: async () => ["device", "action"],
158359
159927
  listExposedEntities: async ({ instanceId }) => {
158360
- ownInstance(instanceId);
158361
- await this.actionExports?.reconcile();
158362
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
158363
- entity: {
158364
- kind: "device",
158365
- deviceId
158366
- },
158367
- exposedAs: m.accessory.displayName
158368
- })), ...this.actionExports?.list() ?? []];
159928
+ const out = [];
159929
+ for (const inst of this.bridgesOf(instanceId)) {
159930
+ await inst.actionExports?.reconcile();
159931
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
159932
+ entity: {
159933
+ kind: "device",
159934
+ deviceId
159935
+ },
159936
+ exposedAs: m.accessory.displayName
159937
+ })), ...inst.actionExports?.list() ?? []);
159938
+ }
159939
+ return out;
158369
159940
  },
158370
159941
  exposeEntity: async ({ instanceId, entity }) => {
158371
- ownInstance(instanceId);
158372
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
158373
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
159942
+ const inst = this.requireBridge(instanceId);
159943
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
159944
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
158374
159945
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158375
159946
  },
158376
159947
  unexposeEntity: async ({ instanceId, entity }) => {
158377
- ownInstance(instanceId);
158378
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
158379
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
159948
+ const inst = this.requireBridge(instanceId);
159949
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
159950
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
158380
159951
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
158381
159952
  },
158382
159953
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
158383
159954
  getDeviceLiveContribution: async () => null,
158384
159955
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
158385
159956
  };
158386
- const clipsProvider = createHksvVideoclipsProvider({
158387
- logger: this.ctx.logger.child("hksv-clips"),
158388
- addonId: EXPORT_HAP_ADDON_ID,
158389
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
158390
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
158391
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
158392
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
158393
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
158394
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
158395
- });
158396
- return [{
158397
- capability: deviceExportCapability,
158398
- provider
158399
- }, {
158400
- capability: videoclipsCapability,
158401
- provider: clipsProvider
158402
- }];
158403
159957
  }
158404
- async onConfigChanged() {
158405
- if (this.config.fixedPin && isValidPincode(this.config.fixedPin) && this.config.identity.pincode !== this.config.fixedPin && this.config.identity.username !== "") {
158406
- const updated = {
158407
- username: this.config.identity.username,
158408
- uuid: this.config.identity.uuid,
158409
- pincode: this.config.fixedPin
158410
- };
158411
- await this.updateGlobalSettings({ identity: updated });
158412
- }
159958
+ requireInstances() {
159959
+ if (this.instances === null) throw new Error("export-hap: instances are not initialised");
159960
+ return this.instances;
158413
159961
  }
158414
- /**
158415
- * Resolve the persistent bridge identity. Empty `username` is the
158416
- * "first boot" sentinel — generate fresh + persist. On subsequent
158417
- * boots the persisted record is reused. An operator-supplied
158418
- * `fixedPin` overrides the persisted pincode (useful for CI replay)
158419
- * but never the username/uuid (those drive the iOS pairing record).
158420
- */
158421
- async ensureIdentity() {
158422
- const current = this.config.identity;
158423
- const fixedPin = this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null;
158424
- if (current.username !== "" && current.uuid !== "" && current.pincode !== "") {
158425
- if (fixedPin && fixedPin !== current.pincode) {
158426
- const updated = {
158427
- username: current.username,
158428
- uuid: current.uuid,
158429
- pincode: fixedPin
158430
- };
158431
- await this.updateGlobalSettings({ identity: updated });
158432
- return updated;
158433
- }
158434
- return current;
158435
- }
158436
- const fresh = {
158437
- username: generateUsername(),
158438
- pincode: fixedPin ?? generatePincode(),
158439
- uuid: buildBridgeUuid(this.config.bridgeName)
159962
+ requireRecords() {
159963
+ const records = this.ctx.records;
159964
+ if (records === void 0) throw new Error("export-hap: records are not available");
159965
+ return records;
159966
+ }
159967
+ /** The ports the identity migration reads and writes through. */
159968
+ identityMigrationPorts() {
159969
+ const handle = this.requireRecords().kind(hapBridgesKind);
159970
+ return {
159971
+ readLegacyIdentity: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]),
159972
+ clearLegacyIdentity: () => this.updateGlobalSettingsAsOperator({ identity: null }),
159973
+ readBridgeName: async () => {
159974
+ const name = (await this.resolveGlobalStore())["bridgeName"];
159975
+ return typeof name === "string" ? name : "";
159976
+ },
159977
+ putDefaultRecord: async (body) => {
159978
+ if (await handle.get("export-hap") !== null) return "exists";
159979
+ try {
159980
+ await handle.put({
159981
+ id: HAP_DEFAULT_INSTANCE_ID,
159982
+ data: body
159983
+ }, { ifRev: 0 });
159984
+ } catch (err) {
159985
+ if (err instanceof RevConflictError) return "exists";
159986
+ throw err;
159987
+ }
159988
+ return "created";
159989
+ },
159990
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
159991
+ patchDefaultName: async (name) => {
159992
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
159993
+ },
159994
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
158440
159995
  };
158441
- await this.updateGlobalSettings({ identity: fresh });
158442
- this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: fresh.username } });
158443
- return fresh;
159996
+ }
159997
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
159998
+ async ensureDefaultBridge() {
159999
+ const handle = this.requireRecords().kind(hapBridgesKind);
160000
+ const boot = await resolveDefaultBridge({
160001
+ readRecord: async () => {
160002
+ const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
160003
+ if (resolved === null) return { kind: "absent" };
160004
+ return resolved.secrets === "resolved" ? {
160005
+ kind: "resolved",
160006
+ body: resolved.body
160007
+ } : { kind: "unavailable" };
160008
+ },
160009
+ legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
160010
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
160011
+ putFresh: async (body) => {
160012
+ await handle.put({
160013
+ id: HAP_DEFAULT_INSTANCE_ID,
160014
+ data: body
160015
+ }, { ifRev: 0 });
160016
+ },
160017
+ mint: () => ({
160018
+ name: DEFAULT_BRIDGE_NAME,
160019
+ username: generateUsername(),
160020
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
160021
+ pincode: generatePincode()
160022
+ })
160023
+ });
160024
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
158444
160025
  }
158445
160026
  /**
158446
160027
  * Build the generic `device-export` `setup` block surfaced via
@@ -158449,10 +160030,10 @@ var ExportHapAddon = class extends BaseAddon {
158449
160030
  * a copyable field, and a short pairing instruction. Returns `null`
158450
160031
  * until the bridge has booted and produced both values.
158451
160032
  */
158452
- buildSetupBlock() {
158453
- const setupCode = this.config.identity.pincode;
160033
+ buildSetupBlock(inst) {
160034
+ const setupCode = inst.pincode;
158454
160035
  if (!setupCode) return null;
158455
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160036
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
158456
160037
  return {
158457
160038
  ...qr !== void 0 ? { qr } : {},
158458
160039
  fields: [{
@@ -158473,18 +160054,18 @@ var ExportHapAddon = class extends BaseAddon {
158473
160054
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
158474
160055
  * still said `streamPreference=auto`.
158475
160056
  */
158476
- async exposeDevice(deviceId, capabilities, settings) {
160057
+ async exposeDevice(inst, deviceId, capabilities, settings) {
158477
160058
  const numericId = Number.parseInt(deviceId, 10);
158478
160059
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158479
- if (this.exposed.has(deviceId)) {
160060
+ if (inst.exposed.has(deviceId)) {
158480
160061
  log.debug("export-hap: device already exposed — refreshing capabilities");
158481
- await this.detachMapper(deviceId);
160062
+ await this.detachMapper(inst, deviceId);
158482
160063
  }
158483
160064
  const summary = await this.fetchDeviceSummary(numericId);
158484
160065
  const mapperKind = pickMapperKind(summary?.type);
158485
160066
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
158486
160067
  const displayName = summary?.name ?? `Device ${deviceId}`;
158487
- const previous = this.config.exposed.find((e) => e.deviceId === deviceId);
160068
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
158488
160069
  const rebuilt = {
158489
160070
  deviceId,
158490
160071
  displayName,
@@ -158496,37 +160077,38 @@ var ExportHapAddon = class extends BaseAddon {
158496
160077
  ...rebuilt,
158497
160078
  settings
158498
160079
  }, previous, ["settings", "capabilities"]);
158499
- const attached = await this.attachMapper(baseEntry);
160080
+ const attached = await this.attachMapper(inst, baseEntry);
158500
160081
  const finalEntry = {
158501
160082
  ...baseEntry,
158502
160083
  childAccessoryUuids: attached.childAccessoryUuids
158503
160084
  };
158504
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
160085
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
158505
160086
  next.push(finalEntry);
158506
- await this.updateGlobalSettings({ exposed: next });
160087
+ await this.setExposedDevices(inst, next);
158507
160088
  if (Number.isFinite(numericId)) {
158508
- const fp = await this.computeExportFingerprint(numericId);
158509
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160089
+ const fp = await this.computeExportFingerprint(inst, numericId);
160090
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
158510
160091
  }
158511
160092
  log.info("export-hap: exposed device", { meta: {
160093
+ instanceId: inst.id,
158512
160094
  displayName,
158513
160095
  mapperKind,
158514
160096
  childCount: attached.childAccessoryUuids.length
158515
160097
  } });
158516
160098
  }
158517
- async unexposeDevice(deviceId, options = {}) {
160099
+ async unexposeDevice(inst, deviceId, options = {}) {
158518
160100
  const numericId = Number.parseInt(deviceId, 10);
158519
160101
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158520
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
158521
- await this.detachMapper(deviceId);
158522
- const next = this.config.exposed.filter((e) => e.deviceId !== deviceId);
158523
- if (next.length !== this.config.exposed.length) await this.updateGlobalSettings({ exposed: next });
158524
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
158525
- await this.forgetFingerprint(numericId);
160102
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160103
+ await this.detachMapper(inst, deviceId);
160104
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160105
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160106
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160107
+ await this.forgetFingerprint(inst, numericId);
158526
160108
  this.hksvBuilds.forget(numericId);
158527
- log.info("export-hap: unexposed device");
160109
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
158528
160110
  }
158529
- async attachMapper(entry) {
160111
+ async attachMapper(inst, entry) {
158530
160112
  const factory = getMapperFactory(entry.mapperKind);
158531
160113
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
158532
160114
  const mapper = await factory({
@@ -158534,6 +160116,7 @@ var ExportHapAddon = class extends BaseAddon {
158534
160116
  deviceId: entry.deviceId,
158535
160117
  displayName: entry.displayName,
158536
160118
  options: {
160119
+ instanceId: inst.id,
158537
160120
  decodeMemos: this.decodeMemos,
158538
160121
  resolveFfmpeg: this.pinnedFfmpeg,
158539
160122
  hksvClipStore: this.hksvClipStore,
@@ -158553,29 +160136,29 @@ var ExportHapAddon = class extends BaseAddon {
158553
160136
  useBridge: entry.settings?.useBridge
158554
160137
  });
158555
160138
  for (const accessory of mapper.accessories) {
158556
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160139
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
158557
160140
  await publishStandalone(accessory, {
158558
- pincode: this.pincode,
160141
+ pincode: inst.pincode,
158559
160142
  port: 0,
158560
160143
  bind: this.bind,
158561
160144
  logger: this.ctx.logger
158562
160145
  });
158563
160146
  }
158564
- this.exposed.set(entry.deviceId, mapper);
160147
+ inst.exposed.set(entry.deviceId, mapper);
158565
160148
  return { childAccessoryUuids: [] };
158566
160149
  }
158567
- async detachMapper(deviceId) {
158568
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160150
+ async detachMapper(inst, deviceId) {
160151
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
158569
160152
  if (pendingTimer) {
158570
160153
  clearTimeout(pendingTimer);
158571
- this.pendingRebuildTimers.delete(deviceId);
160154
+ inst.pendingRebuildTimers.delete(deviceId);
158572
160155
  }
158573
- const mapper = this.exposed.get(deviceId);
160156
+ const mapper = inst.exposed.get(deviceId);
158574
160157
  if (!mapper) return;
158575
- this.exposed.delete(deviceId);
160158
+ inst.exposed.delete(deviceId);
158576
160159
  for (const accessory of mapper.accessories) {
158577
- if (this.bridgeHost?.holds(accessory) === true) {
158578
- this.bridgeHost.remove(accessory);
160160
+ if (inst.bridgeHost.holds(accessory)) {
160161
+ inst.bridgeHost.remove(accessory);
158579
160162
  continue;
158580
160163
  }
158581
160164
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -158584,21 +160167,22 @@ var ExportHapAddon = class extends BaseAddon {
158584
160167
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
158585
160168
  });
158586
160169
  }
158587
- requireActionExports() {
158588
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
158589
- return this.actionExports;
160170
+ requireActionExports(inst) {
160171
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160172
+ return inst.actionExports;
158590
160173
  }
158591
- async detachAll() {
158592
- const ids = Array.from(this.exposed.keys());
158593
- for (const id of ids) await this.detachMapper(id);
160174
+ async detachAll(inst) {
160175
+ const ids = Array.from(inst.exposed.keys());
160176
+ for (const id of ids) await this.detachMapper(inst, id);
158594
160177
  }
158595
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
158596
- * on detach so stale timers can't republish a removed accessory. */
158597
- pendingRebuildTimers = /* @__PURE__ */ new Map();
158598
160178
  /** Deterministic HAP accessory UUID for a device — the same one the
158599
160179
  * orchestrator built it with (`mappers/kind.ts`). */
158600
- hapAccessoryUuid(deviceId) {
158601
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160180
+ hapAccessoryUuid(inst, deviceId) {
160181
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160182
+ }
160183
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160184
+ syncStateOf(inst) {
160185
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
158602
160186
  }
158603
160187
  /**
158604
160188
  * Export fingerprint of a device from its PERSISTED features + type
@@ -158616,7 +160200,7 @@ var ExportHapAddon = class extends BaseAddon {
158616
160200
  * A brand-new un-probed device with no persisted entry falls back to its
158617
160201
  * fresh fingerprint (publishes once, acceptable).
158618
160202
  */
158619
- async computeExportFingerprint(deviceId) {
160203
+ async computeExportFingerprint(inst, deviceId) {
158620
160204
  try {
158621
160205
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
158622
160206
  if (!device) return null;
@@ -158625,10 +160209,10 @@ var ExportHapAddon = class extends BaseAddon {
158625
160209
  deviceType: device.type,
158626
160210
  features: device.features
158627
160211
  });
158628
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160212
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
158629
160213
  const withToken = withRecordabilityToken({
158630
160214
  base: fresh,
158631
- token: await this.readRecordabilityToken(deviceId, device.type),
160215
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
158632
160216
  persisted
158633
160217
  });
158634
160218
  return resolveExportFingerprint({
@@ -158648,12 +160232,12 @@ var ExportHapAddon = class extends BaseAddon {
158648
160232
  * republish every non-camera accessory once for nothing) and for a camera
158649
160233
  * whose profiles could not be read right now.
158650
160234
  */
158651
- async readRecordabilityToken(deviceId, type) {
160235
+ async readRecordabilityToken(inst, deviceId, type) {
158652
160236
  if (pickMapperKind(type) !== "camera") return null;
158653
160237
  try {
158654
160238
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
158655
160239
  return recordabilityTokenFor({
158656
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160240
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
158657
160241
  entries: entries ?? null
158658
160242
  });
158659
160243
  } catch {
@@ -158662,20 +160246,20 @@ var ExportHapAddon = class extends BaseAddon {
158662
160246
  }
158663
160247
  /** Persist a device's current export fingerprint into `exportSyncState`
158664
160248
  * (best-effort; called after a successful attach). */
158665
- async persistFingerprint(deviceId, fingerprint) {
158666
- const state = syncStateFromJson(this.config.exportSyncState);
160249
+ async persistFingerprint(inst, deviceId, fingerprint) {
160250
+ const state = this.syncStateOf(inst);
158667
160251
  state.set(deviceId, {
158668
160252
  fingerprint,
158669
- externalIds: [this.hapAccessoryUuid(deviceId)]
160253
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
158670
160254
  });
158671
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160255
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
158672
160256
  }
158673
160257
  /** Drop a device's `exportSyncState` entry (on unexpose). */
158674
- async forgetFingerprint(deviceId) {
158675
- const state = syncStateFromJson(this.config.exportSyncState);
160258
+ async forgetFingerprint(inst, deviceId) {
160259
+ const state = this.syncStateOf(inst);
158676
160260
  if (!state.has(deviceId)) return;
158677
160261
  state.delete(deviceId);
158678
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160262
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
158679
160263
  }
158680
160264
  /**
158681
160265
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -158706,34 +160290,23 @@ var ExportHapAddon = class extends BaseAddon {
158706
160290
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
158707
160291
  if (deviceIdNumeric === null) return;
158708
160292
  const deviceId = String(deviceIdNumeric);
158709
- if (!this.findEntry(deviceIdNumeric)) return;
158710
- const existing = this.pendingRebuildTimers.get(deviceId);
158711
- if (existing) clearTimeout(existing);
158712
- const timer = setTimeout(() => {
158713
- this.pendingRebuildTimers.delete(deviceId);
158714
- this.reconcileDevice(deviceId);
158715
- }, 500);
158716
- if (typeof timer.unref === "function") timer.unref();
158717
- this.pendingRebuildTimers.set(deviceId, timer);
160293
+ for (const inst of this.bridges.values()) {
160294
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160295
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160296
+ if (existing) clearTimeout(existing);
160297
+ const timer = setTimeout(() => {
160298
+ inst.pendingRebuildTimers.delete(deviceId);
160299
+ this.reconcileDevice(inst, deviceId);
160300
+ }, 500);
160301
+ if (typeof timer.unref === "function") timer.unref();
160302
+ inst.pendingRebuildTimers.set(deviceId, timer);
160303
+ }
158718
160304
  });
158719
160305
  this.ctx.addDisposer(async () => {
158720
160306
  unsubscribe();
158721
160307
  });
158722
160308
  }
158723
160309
  /**
158724
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
158725
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
158726
- * per-device timers into `pendingRebuildTimers` but never clear the map on
158727
- * their own teardown — that shared resource is cleared here, exactly once, on
158728
- * shutdown.
158729
- */
158730
- disposeSharedRebuildTimers() {
158731
- this.ctx.addDisposer(async () => {
158732
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
158733
- this.pendingRebuildTimers.clear();
158734
- });
158735
- }
158736
- /**
158737
160310
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
158738
160311
  * its persisted export shape changes. `DeviceProvisioned` is gated by
158739
160312
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -158763,22 +160336,22 @@ var ExportHapAddon = class extends BaseAddon {
158763
160336
  * Errors are logged and swallowed — a failed reconcile leaves the prior
158764
160337
  * accessory up, which is strictly better than removing it.
158765
160338
  */
158766
- async reconcileDevice(deviceId) {
160339
+ async reconcileDevice(inst, deviceId) {
158767
160340
  const numericId = Number.parseInt(deviceId, 10);
158768
160341
  if (!Number.isFinite(numericId)) return;
158769
- const entry = this.findEntry(numericId);
160342
+ const entry = inst.findEntry(numericId);
158770
160343
  if (!entry) return;
158771
160344
  const log = this.ctx.logger.withTags({ deviceId: numericId });
158772
- const current = await this.computeExportFingerprint(numericId);
160345
+ const current = await this.computeExportFingerprint(inst, numericId);
158773
160346
  if (current === null) {
158774
160347
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
158775
160348
  return;
158776
160349
  }
158777
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160350
+ const last = this.syncStateOf(inst).get(numericId);
158778
160351
  if (last?.fingerprint === current) {
158779
- if (!this.exposed.has(deviceId)) try {
158780
- await this.attachMapper(entry);
158781
- await this.persistFingerprint(numericId, current);
160352
+ if (!inst.exposed.has(deviceId)) try {
160353
+ await this.attachMapper(inst, entry);
160354
+ await this.persistFingerprint(inst, numericId, current);
158782
160355
  } catch (err) {
158783
160356
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
158784
160357
  }
@@ -158790,9 +160363,9 @@ var ExportHapAddon = class extends BaseAddon {
158790
160363
  to: current.slice(0, 12)
158791
160364
  } });
158792
160365
  try {
158793
- await this.detachMapper(deviceId);
158794
- await this.attachMapper(entry);
158795
- await this.persistFingerprint(numericId, current);
160366
+ await this.detachMapper(inst, deviceId);
160367
+ await this.attachMapper(inst, entry);
160368
+ await this.persistFingerprint(inst, numericId, current);
158796
160369
  } catch (err) {
158797
160370
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
158798
160371
  }
@@ -158855,7 +160428,7 @@ var ExportHapAddon = class extends BaseAddon {
158855
160428
  return null;
158856
160429
  }
158857
160430
  }
158858
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160431
+ /** The one declaration of the bind-interface field: a fact of one node. */
158859
160432
  interfaceNameField() {
158860
160433
  return this.field({
158861
160434
  type: "text",
@@ -158875,58 +160448,53 @@ var ExportHapAddon = class extends BaseAddon {
158875
160448
  fields: [this.interfaceNameField()]
158876
160449
  }] }) : null;
158877
160450
  }
160451
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160452
+ async deviceDefaultsSchema(cap) {
160453
+ return cap === "device-export" ? this.schema({ sections: [{
160454
+ id: "export-hap-defaults",
160455
+ title: "HomeKit Export",
160456
+ fields: [this.field({
160457
+ type: "number",
160458
+ key: "clipRetentionDays",
160459
+ label: "Keep HomeKit clips for (days)",
160460
+ description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
160461
+ default: DEFAULT_CONFIG.clipRetentionDays,
160462
+ placement: { tab: "advanced" }
160463
+ })]
160464
+ }] }) : null;
160465
+ }
158878
160466
  /**
158879
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
158880
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
158881
- * value the migration wrote.
160467
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160468
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160469
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160470
+ * config when anything landed, so this boot binds the value the migration wrote.
158882
160471
  */
158883
160472
  async migrateSettings() {
158884
160473
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
158885
160474
  readStored: (keys) => readRawKeys((key) => this.readStoredGlobalKey(key), "export-hap", keys),
158886
- storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin })
160475
+ storeFixedPin: (pin) => this.updateGlobalSettingsAsOperator({ fixedPin: pin }),
160476
+ ...this.identityMigrationPorts(),
160477
+ ...this.exposureMigrationPorts()
158887
160478
  }))).applied.length > 0) await this.resolveConfig();
158888
160479
  }
160480
+ /**
160481
+ * Only the declaration `perNodeKeys()` derives the node-scoped keys from: `interfaceName` is a
160482
+ * fact of one node, and the settings machinery reads a per-node key through this schema. The
160483
+ * editable surfaces are the node form, the device defaults and each bridge's own form.
160484
+ */
158889
160485
  globalSettingsSchema() {
158890
160486
  return this.schema({ sections: [{
158891
160487
  id: "export-hap",
158892
160488
  title: "HomeKit Export",
158893
- description: "Publishes each exposed device as its own HomeKit accessory, sharing one setup code. Mark a device \"Expose to HomeKit\" on its settings page, then add it in the iOS Home app (+ → Add Accessory) and enter the setup code shown there.",
158894
- columns: 1,
158895
- fields: [
158896
- this.field({
158897
- type: "text",
158898
- key: "bridgeName",
158899
- label: "Installation name",
158900
- description: "The name of the shared bridge that carries every exposed device that is not a camera (switches, sensors, locks, alarm panels) — what iOS Home lists under Add Accessory. Cameras are never bridged: each one is published as its own accessory under its device name. Set it before you add the bridge in iOS Home.",
158901
- default: DEFAULT_CONFIG.bridgeName,
158902
- requiresRestart: true,
158903
- placement: { tab: "advanced" }
158904
- }),
158905
- this.field({
158906
- type: "password",
158907
- key: "fixedPin",
158908
- label: "Fixed setup code (XXX-XX-XXX)",
158909
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
158910
- default: DEFAULT_CONFIG.fixedPin,
158911
- requiresRestart: true,
158912
- placement: { tab: "advanced" }
158913
- }),
158914
- this.interfaceNameField(),
158915
- this.field({
158916
- type: "number",
158917
- key: "clipRetentionDays",
158918
- label: "Keep HomeKit clips for (days)",
158919
- description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
158920
- default: DEFAULT_CONFIG.clipRetentionDays,
158921
- placement: { tab: "advanced" }
158922
- })
158923
- ]
160489
+ fields: [this.interfaceNameField()]
158924
160490
  }] });
158925
160491
  }
158926
160492
  async buildDeviceSettingsContribution(deviceId) {
158927
160493
  const kind = await this.resolveExportKind(deviceId);
158928
160494
  if (kind === null) return null;
158929
- const entry = this.findEntry(deviceId);
160495
+ const inst = this.instanceForDevice(deviceId);
160496
+ if (inst === null) return null;
160497
+ const entry = inst.findEntry(deviceId);
158930
160498
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
158931
160499
  const enabled = entry !== null;
158932
160500
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -158936,13 +160504,13 @@ var ExportHapAddon = class extends BaseAddon {
158936
160504
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
158937
160505
  const keepClipsKey = `hap:${deviceId}:keepClips`;
158938
160506
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
158939
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160507
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
158940
160508
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
158941
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160509
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
158942
160510
  const name = entry?.displayName ?? `Device ${deviceId}`;
158943
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
158944
- 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}.`;
158945
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160511
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160512
+ const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${inst.name}” bridge, as “${name}”` : `On the “${inst.name}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${inst.name}”, then enter setup code ${inst.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 ${inst.pincode}.`;
160513
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
158946
160514
  let qrValue = "";
158947
160515
  if (qrSource) try {
158948
160516
  qrValue = qrSource.setupURI();
@@ -158984,7 +160552,7 @@ var ExportHapAddon = class extends BaseAddon {
158984
160552
  type: "info",
158985
160553
  key: `hap:${deviceId}:hksvRecordingStatus`,
158986
160554
  label: "HomeKit recording (Secure Video)",
158987
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160555
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
158988
160556
  showWhen: {
158989
160557
  field: enabledKey,
158990
160558
  equals: true
@@ -159068,7 +160636,7 @@ var ExportHapAddon = class extends BaseAddon {
159068
160636
  type: "qr-code",
159069
160637
  key: "__hap-pair-qr",
159070
160638
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
159071
- 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}.`,
160639
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
159072
160640
  value: qrValue,
159073
160641
  size: 192,
159074
160642
  alt: `HomeKit pairing QR for ${name}`,
@@ -159107,8 +160675,10 @@ var ExportHapAddon = class extends BaseAddon {
159107
160675
  async applyDeviceSettingsPatch(deviceId, patch) {
159108
160676
  const deviceIdStr = String(deviceId);
159109
160677
  const log = this.ctx.logger.withTags({ deviceId });
159110
- const current = this.findEntry(deviceId);
159111
- const wasEnabled = this.exposed.has(deviceIdStr);
160678
+ const inst = this.instanceForDevice(deviceId);
160679
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160680
+ const current = inst.findEntry(deviceId);
160681
+ const wasEnabled = inst.exposed.has(deviceIdStr);
159112
160682
  const enabledKey = `hap:${deviceId}:enabled`;
159113
160683
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
159114
160684
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -159137,12 +160707,12 @@ var ExportHapAddon = class extends BaseAddon {
159137
160707
  clipRetentionDays
159138
160708
  };
159139
160709
  if (!enabledValue) {
159140
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160710
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
159141
160711
  return { success: true };
159142
160712
  }
159143
160713
  if (!wasEnabled) {
159144
- await this.exposeDevice(deviceIdStr);
159145
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160714
+ await this.exposeDevice(inst, deviceIdStr);
160715
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
159146
160716
  return { success: true };
159147
160717
  }
159148
160718
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -159156,7 +160726,7 @@ var ExportHapAddon = class extends BaseAddon {
159156
160726
  mapperKind,
159157
160727
  useBridge
159158
160728
  });
159159
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160729
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
159160
160730
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
159161
160731
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
159162
160732
  streamPreference: {
@@ -159173,8 +160743,8 @@ var ExportHapAddon = class extends BaseAddon {
159173
160743
  }
159174
160744
  } });
159175
160745
  try {
159176
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
159177
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160746
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160747
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
159178
160748
  } catch (err) {
159179
160749
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
159180
160750
  }
@@ -159232,16 +160802,71 @@ var ExportHapAddon = class extends BaseAddon {
159232
160802
  const planes = this.hksvClipPlanes;
159233
160803
  return `/addon/${EXPORT_HAP_ADDON_ID}/${kind === "media" ? planes?.mediaPrefix ?? "hksv-clip" : planes?.thumbPrefix ?? "hksv-clip-thumb"}/${String(deviceId)}/${stem}.${kind === "media" ? "mp4" : "jpg"}`;
159234
160804
  }
159235
- findEntry(deviceId) {
159236
- const id = String(deviceId);
159237
- return this.config.exposed.find((e) => e.deviceId === id) ?? null;
160805
+ /** The exposure record's handle: one row per bridge instance, under the instance id. */
160806
+ exposureHandle() {
160807
+ return this.requireRecords().kind(hapBridgeExportsKind);
160808
+ }
160809
+ /** Load a bridge's exposure record; create it empty when none exists. */
160810
+ async loadExposure(id) {
160811
+ const handle = this.exposureHandle();
160812
+ const row = await handle.get(id);
160813
+ if (row !== null) return row.data;
160814
+ const empty = {
160815
+ name: HAP_EXPOSURE_NAME,
160816
+ devices: [],
160817
+ actions: []
160818
+ };
160819
+ await handle.put({
160820
+ id,
160821
+ data: empty
160822
+ }, { ifRev: 0 });
160823
+ return empty;
160824
+ }
160825
+ async writeExposure(inst, next) {
160826
+ await this.exposureHandle().put({
160827
+ id: inst.id,
160828
+ data: next
160829
+ });
160830
+ inst.exposure = next;
160831
+ }
160832
+ setExposedDevices(inst, devices) {
160833
+ return this.writeExposure(inst, {
160834
+ ...inst.exposure,
160835
+ devices
160836
+ });
160837
+ }
160838
+ setExposedActions(inst, actions) {
160839
+ return this.writeExposure(inst, {
160840
+ ...inst.exposure,
160841
+ actions
160842
+ });
160843
+ }
160844
+ /** The ports the exposure migration reads and writes through. */
160845
+ exposureMigrationPorts() {
160846
+ const handle = this.exposureHandle();
160847
+ return {
160848
+ putExposure: async (body) => {
160849
+ if (await handle.get("export-hap") !== null) return "exists";
160850
+ try {
160851
+ await handle.put({
160852
+ id: HAP_DEFAULT_INSTANCE_ID,
160853
+ data: body
160854
+ }, { ifRev: 0 });
160855
+ } catch (err) {
160856
+ if (err instanceof RevConflictError) return "exists";
160857
+ throw err;
160858
+ }
160859
+ return "created";
160860
+ },
160861
+ readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160862
+ };
159238
160863
  }
159239
- async updateEntrySettings(deviceIdStr, settings) {
159240
- const next = this.config.exposed.map((e) => e.deviceId === deviceIdStr ? {
160864
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160865
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
159241
160866
  ...e,
159242
160867
  settings
159243
160868
  } : e);
159244
- await this.updateGlobalSettings({ exposed: next });
160869
+ await this.setExposedDevices(inst, next);
159245
160870
  }
159246
160871
  };
159247
160872
  function errMsg(err) {
@@ -159256,6 +160881,7 @@ exports.default = ExportHapAddon;
159256
160881
  exports.__toCommonJS = __toCommonJS;
159257
160882
  exports.deriveUsername = deriveUsername;
159258
160883
  exports.describeHksvCamera = describeHksvCamera;
160884
+ exports.exportHapActions = exportHapActions;
159259
160885
  exports.initHapStorage = initHapStorage;
159260
160886
  exports.publishStandalone = publishStandalone;
159261
160887
  exports.resolveClipRetentionDays = resolveClipRetentionDays;