@camstack/addon-export-hap 1.2.192 → 1.2.194

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);
@@ -6031,7 +6031,7 @@ var ZodIssueCode = {
6031
6031
  var ZodFirstPartyTypeKind;
6032
6032
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6033
6033
  //#endregion
6034
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6034
+ //#region ../types/dist/sleep-DEZaLbiu.mjs
6035
6035
  /**
6036
6036
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6037
6037
  * window to float samples (D455).
@@ -6631,7 +6631,7 @@ var NOT_RUN = {
6631
6631
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6632
6632
  * because the hub (and this addon's boot) must not hang on a migration.
6633
6633
  */
6634
- async function runAddonMigrations(host, migrations, logger) {
6634
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6635
6635
  const first = migrations[0];
6636
6636
  if (first === void 0) return NOT_RUN;
6637
6637
  const owner = first.meta.owner;
@@ -6660,7 +6660,9 @@ async function runAddonMigrations(host, migrations, logger) {
6660
6660
  else if (status === "blocked") blocked.push(id);
6661
6661
  else skipped.push(id);
6662
6662
  };
6663
+ const selected = options.only === void 0 ? null : new Set(options.only);
6663
6664
  for (const step of declaration.steps) {
6665
+ if (selected !== null && !selected.has(step.id)) continue;
6664
6666
  const bound = byId.get(step.id);
6665
6667
  if (bound === void 0 || step.action === "skip") {
6666
6668
  skipped.push(step.id);
@@ -6838,6 +6840,12 @@ function projectStore(store, perNodeKeys, nodeId) {
6838
6840
  }
6839
6841
  return out;
6840
6842
  }
6843
+ /** Every scope, in the order the guard and the docs list them. */
6844
+ var SCOPED_SETTINGS_SCOPES = [
6845
+ "cluster",
6846
+ "device-defaults",
6847
+ "node"
6848
+ ];
6841
6849
  /**
6842
6850
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6843
6851
  *
@@ -7729,6 +7737,13 @@ var BaseAddon = class {
7729
7737
  */
7730
7738
  secretStatePaths = [];
7731
7739
  _addonSecretTree = null;
7740
+ /**
7741
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
7742
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
7743
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
7744
+ */
7745
+ _scopedByCap = /* @__PURE__ */ new Map();
7746
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7732
7747
  _deviceSecretTree = null;
7733
7748
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7734
7749
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7798,6 +7813,7 @@ var BaseAddon = class {
7798
7813
  this._ctx = context;
7799
7814
  this._secretSettings = null;
7800
7815
  }
7816
+ await this.loadScopedSchemas();
7801
7817
  await this.resolveConfig();
7802
7818
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7803
7819
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7807,6 +7823,7 @@ var BaseAddon = class {
7807
7823
  const normalized = normalizeAddonInitResult(result);
7808
7824
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7809
7825
  this._registeredCapNames = providers.map((p) => p.capability.name);
7826
+ await this.loadScopedSchemas();
7810
7827
  return normalized;
7811
7828
  }
7812
7829
  /**
@@ -7820,14 +7837,18 @@ var BaseAddon = class {
7820
7837
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7821
7838
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7822
7839
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7840
+ *
7841
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7842
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7843
+ * omitted applied ids "newer").
7823
7844
  */
7824
- async runMigrations(migrations) {
7845
+ async runMigrations(migrations, options) {
7825
7846
  const api = this.ctx.api.migrations;
7826
7847
  const report = await runAddonMigrations({
7827
7848
  declareOwner: (input) => api.declareOwner.mutate(input),
7828
7849
  startMigration: (input) => api.startMigration.mutate(input),
7829
7850
  finishMigration: (input) => api.finishMigration.mutate(input)
7830
- }, migrations, this.ctx.logger);
7851
+ }, migrations, this.ctx.logger, options);
7831
7852
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7832
7853
  return report;
7833
7854
  }
@@ -7891,6 +7912,16 @@ var BaseAddon = class {
7891
7912
  schema(schema) {
7892
7913
  return schema;
7893
7914
  }
7915
+ /**
7916
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
7917
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
7918
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
7919
+ * must already know which keys are per node. Names the providers register at init are added
7920
+ * once known.
7921
+ */
7922
+ scopedSettingsCapabilities() {
7923
+ return [];
7924
+ }
7894
7925
  /** Override to provide global-level settings UI schema. */
7895
7926
  globalSettingsSchema(_cap) {
7896
7927
  return null;
@@ -7934,7 +7965,8 @@ var BaseAddon = class {
7934
7965
  return [];
7935
7966
  }
7936
7967
  async getGlobalSettings(overlay, cap, nodeId) {
7937
- const schema = this.globalSettingsSchema(cap);
7968
+ await this.loadScopedSchemas(cap);
7969
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7938
7970
  if (!schema) return { sections: [] };
7939
7971
  const projected = await this.readRawProjectedStore(nodeId, cap);
7940
7972
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -7969,10 +8001,9 @@ var BaseAddon = class {
7969
8001
  *
7970
8002
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7971
8003
  * needs its connection fields, the default integration the addon's own sections. It is the
7972
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7973
- * unchanged (`integrations.setSettings` for an account integration).
8004
+ * SHAPE of the form only — the values live on the instance record.
7974
8005
  */
7975
- async integrationSettingsSchema(_instance) {
8006
+ async integrationFormSchema(_instance) {
7976
8007
  return null;
7977
8008
  }
7978
8009
  /**
@@ -8018,7 +8049,7 @@ var BaseAddon = class {
8018
8049
  * per-instance schema when it declares one, else its global schema (what they always showed).
8019
8050
  */
8020
8051
  async getIntegrationFormSchema(instance, nodeId) {
8021
- const scoped = await this.integrationSettingsSchema(instance);
8052
+ const scoped = await this.integrationFormSchema(instance);
8022
8053
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
8023
8054
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
8024
8055
  }
@@ -8066,6 +8097,7 @@ var BaseAddon = class {
8066
8097
  * resolved blob back is a no-op for every unchanged secret.
8067
8098
  */
8068
8099
  async resolveGlobalStore(nodeId, cap) {
8100
+ await this.loadScopedSchemas(cap);
8069
8101
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8070
8102
  return this.projectForNode(raw, nodeId, cap);
8071
8103
  }
@@ -8076,6 +8108,7 @@ var BaseAddon = class {
8076
8108
  }
8077
8109
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8078
8110
  async readRawProjectedStore(nodeId, cap) {
8111
+ await this.loadScopedSchemas(cap);
8079
8112
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8080
8113
  return this.projectForNode(raw, nodeId, cap);
8081
8114
  }
@@ -8178,6 +8211,7 @@ var BaseAddon = class {
8178
8211
  await this.applyGlobalPatch(patch, nodeId);
8179
8212
  }
8180
8213
  async applyGlobalPatch(barePatch, nodeId) {
8214
+ await this.loadScopedSchemas();
8181
8215
  const keys = this.perNodeKeys();
8182
8216
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8183
8217
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8191,7 +8225,8 @@ var BaseAddon = class {
8191
8225
  await this.resolveConfig();
8192
8226
  await this.onConfigChanged();
8193
8227
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8194
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8228
+ const legacy = this.globalSettingsSchema();
8229
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8195
8230
  }
8196
8231
  /**
8197
8232
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8199,14 +8234,67 @@ var BaseAddon = class {
8199
8234
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8200
8235
  * settings API behaves exactly like the legacy node-agnostic one.
8201
8236
  */
8202
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8237
+ /**
8238
+ * Load the scoped schemas of every capability this addon declares (the override and the
8239
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8240
+ * derived from the previous set. Idempotent.
8241
+ */
8242
+ async loadScopedSchemas(extraCap) {
8243
+ const caps = new Set([
8244
+ ...this.scopedSettingsCapabilities(),
8245
+ ...this._registeredCapNames,
8246
+ ...extraCap === void 0 ? [] : [extraCap]
8247
+ ]);
8248
+ let added = false;
8249
+ for (const cap of caps) {
8250
+ if (this._scopedByCap.has(cap)) continue;
8251
+ const loaded = [];
8252
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8253
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8254
+ if (schema !== null) loaded.push({
8255
+ scope,
8256
+ schema
8257
+ });
8258
+ }
8259
+ this._scopedByCap.set(cap, loaded);
8260
+ added = true;
8261
+ }
8262
+ if (!added) return;
8263
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8264
+ this._addonSecretTree = null;
8265
+ }
8266
+ /**
8267
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8268
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8269
+ */
8270
+ scopedFormSchema(cap) {
8271
+ const byId = /* @__PURE__ */ new Map();
8272
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8273
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
8274
+ }
8275
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
8276
+ loadedScopedSchemas(cap) {
8277
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
8278
+ return [...this._scopedByCap.values()].flat();
8279
+ }
8280
+ /**
8281
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
8282
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
8283
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
8284
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
8285
+ * Call {@link loadScopedSchemas} first (the async seams do).
8286
+ */
8203
8287
  perNodeKeys(cap) {
8204
8288
  const cacheKey = cap ?? "";
8205
- const cached = this._perNodeKeysCache.get(cacheKey);
8289
+ const cached = this._nodeKeysByCap.get(cacheKey);
8206
8290
  if (cached) return cached;
8207
- const schema = this.globalSettingsSchema(cap);
8208
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8209
- this._perNodeKeysCache.set(cacheKey, keys);
8291
+ const legacy = this.globalSettingsSchema(cap);
8292
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8293
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
8294
+ if (scope !== "node") continue;
8295
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
8296
+ }
8297
+ this._nodeKeysByCap.set(cacheKey, keys);
8210
8298
  return keys;
8211
8299
  }
8212
8300
  /**
@@ -8216,10 +8304,9 @@ var BaseAddon = class {
8216
8304
  * time to return its response before the addon is torn down and
8217
8305
  * re-initialised by `AddonRegistryService.restartAddon`.
8218
8306
  */
8219
- maybeAutoRestart(patchKeys, schema) {
8220
- if (!schema) return;
8307
+ maybeAutoRestart(patchKeys, schemas) {
8221
8308
  const restartKeys = /* @__PURE__ */ new Set();
8222
- for (const section of schema.sections) for (const field of section.fields) {
8309
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8223
8310
  if (field.type === "separator" || field.type === "info") continue;
8224
8311
  if (field.requiresRestart) restartKeys.add(field.key);
8225
8312
  }
@@ -8415,12 +8502,14 @@ var BaseAddon = class {
8415
8502
  * here, in the addon's own process, so the hub keeps no copy of it.
8416
8503
  */
8417
8504
  async getDeclaredSettingsKeys() {
8505
+ await this.loadScopedSchemas();
8418
8506
  return { keys: [...this.declaredKeySet()].toSorted() };
8419
8507
  }
8420
8508
  declaredKeySet() {
8421
8509
  const keys = new Set(Object.keys(this.defaults));
8422
8510
  const schema = this.globalSettingsSchema();
8423
8511
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8512
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8424
8513
  for (const key of this._declaredStateKeys) keys.add(key);
8425
8514
  for (const path of this.secretStatePaths) {
8426
8515
  const root = path.split(/[.[]/, 1)[0];
@@ -8516,7 +8605,11 @@ var BaseAddon = class {
8516
8605
  }
8517
8606
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8518
8607
  addonSecretTree() {
8519
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
8608
+ if (this._addonSecretTree === null) {
8609
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
8610
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
8611
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
8612
+ }
8520
8613
  return this._addonSecretTree;
8521
8614
  }
8522
8615
  deviceSecretTree() {
@@ -8766,6 +8859,23 @@ function dropPerNodeFields(fields) {
8766
8859
  }
8767
8860
  return kept;
8768
8861
  }
8862
+ /** The keys of the value-holding fields, recursing into layout containers. */
8863
+ function collectValueFieldKeys(fields) {
8864
+ const collected = [];
8865
+ for (const field of fields) {
8866
+ if (field.type === "group") {
8867
+ collected.push(...collectValueFieldKeys(field.fields));
8868
+ continue;
8869
+ }
8870
+ if (field.type === "sub-tabs") {
8871
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
8872
+ continue;
8873
+ }
8874
+ if (field.type === "separator" || field.type === "info") continue;
8875
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
8876
+ }
8877
+ return collected;
8878
+ }
8769
8879
  function collectFieldKeys(fields) {
8770
8880
  const collected = [];
8771
8881
  for (const field of fields) {
@@ -9285,6 +9395,7 @@ function defineEntryKind(name, spec) {
9285
9395
  class: "config",
9286
9396
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9287
9397
  retention: { none: "an entry goes only when the operator deletes it" },
9398
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9288
9399
  ...spec.database === void 0 ? {} : { database: spec.database },
9289
9400
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9290
9401
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -9981,6 +10092,28 @@ function toNodeId(idOrRunnerId) {
9981
10092
  const head = idOrRunnerId.split("/")[0];
9982
10093
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9983
10094
  }
10095
+ /**
10096
+ * Identity — preserves literal types for downstream inference.
10097
+ *
10098
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
10099
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
10100
+ * the broader unions declared on `CustomActionSpec`'s default generics.
10101
+ * Shape validity is enforced separately by the `customAction(...)` helper
10102
+ * whose return type is already a `CustomActionSpec<...>`.
10103
+ */
10104
+ function defineCustomActions(spec) {
10105
+ return spec;
10106
+ }
10107
+ function customAction(input, output, options) {
10108
+ return {
10109
+ input,
10110
+ output,
10111
+ kind: options?.kind ?? "query",
10112
+ auth: options?.auth ?? "protected",
10113
+ scope: options?.scope ?? { kind: "system" },
10114
+ ...options?.caller ? { caller: "required" } : {}
10115
+ };
10116
+ }
9984
10117
  Object.freeze({ "doorbell": "lastPressedAt" });
9985
10118
  /** Every capability name, so addon code can check a name without the schema graph. */
9986
10119
  var CAP_NAMES = Object.freeze([
@@ -12009,7 +12142,7 @@ object({
12009
12142
  params: record(string(), union([string(), number()])).optional()
12010
12143
  });
12011
12144
  //#endregion
12012
- //#region ../types/dist/composition-CRNwcFYY.mjs
12145
+ //#region ../types/dist/composition-pOHbTzRB.mjs
12013
12146
  var AUDIO_ENCODER_BY_CODEC = {
12014
12147
  opus: "libopus",
12015
12148
  aac: "aac",
@@ -15266,7 +15399,13 @@ var MigrationLedgerEntrySchema = object({
15266
15399
  * joined by the engine from the catalogues it knows this boot. Absent when no
15267
15400
  * catalogue lists the id (a newer database).
15268
15401
  */
15269
- meta: MigrationMetaSchema.optional()
15402
+ meta: MigrationMetaSchema.optional(),
15403
+ /**
15404
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15405
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15406
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15407
+ */
15408
+ ownerNotLoaded: boolean().optional()
15270
15409
  });
15271
15410
  /** A catalogued migration that is not applied, with where it stands. */
15272
15411
  var MigrationPendingEntrySchema = object({
@@ -50014,6 +50153,9 @@ var RunningProposalEvidenceSchema = object({
50014
50153
  runsFound: number().int().nonnegative(),
50015
50154
  pausesFound: number().int().nonnegative(),
50016
50155
  longestPauseMs: number().nonnegative(),
50156
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50157
+ pulsesFound: number().int().nonnegative(),
50158
+ longestPulseMs: number().nonnegative(),
50017
50159
  idleFloorW: number(),
50018
50160
  noiseCeilingW: number(),
50019
50161
  plateauW: number(),
@@ -51240,13 +51382,6 @@ var ExportInstanceUnknownError = class extends Error {
51240
51382
  function statusInstanceOf(input) {
51241
51383
  return "instanceId" in input ? input.instanceId : void 0;
51242
51384
  }
51243
- /**
51244
- * A single-instance provider's check: an absent id or its own passes, any other throws
51245
- * `ExportInstanceUnknownError`.
51246
- */
51247
- function assertOwnExportInstance(addon, own, instanceId) {
51248
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51249
- }
51250
51385
  var LinkStateSchema = _enum([
51251
51386
  "unlinked",
51252
51387
  "linked",
@@ -51351,12 +51486,12 @@ var deviceExportCapability = {
51351
51486
  kind: "poll"
51352
51487
  },
51353
51488
  /**
51354
- * Each export provider contributes its own per-device "Export" panel
51355
- * (enabled toggle, preferred stream, addon-specific knobs like the
51356
- * HA-MQTT discovery prefix). The three framework methods
51357
- * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /
51358
- * `applyDeviceSettingsPatch` are auto-injected on the provider
51359
- * interface and routed to the device-details aggregator.
51489
+ * Each export provider MAY contribute its own per-device "Export" panel
51490
+ * (enabled toggle, preferred stream, addon-specific knobs). The three
51491
+ * framework methods are mounted on the cap router when present.
51492
+ * `IDeviceExportProvider` leaves them optional: an exporter with no
51493
+ * per-device panel omits them (a `deviceConfig` cap's UI is derived and
51494
+ * never hand-written — D14 — and an exporter is not one of those).
51360
51495
  */
51361
51496
  exposesDeviceSettings: true,
51362
51497
  methods: {
@@ -55063,11 +55198,7 @@ var CreateIntegrationInputSchema = object({
55063
55198
  info: record(string(), unknown()).optional(),
55064
55199
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
55065
55200
  originStableId: string().optional(),
55066
- settings: record(string(), unknown()).optional(),
55067
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
55068
- * the keychain, not the table (D787). */
55069
- secretKeys: array(string()).optional(),
55070
- skipRestart: boolean().optional()
55201
+ settings: record(string(), unknown()).optional()
55071
55202
  });
55072
55203
  var UpdateIntegrationInputSchema = object({
55073
55204
  id: string(),
@@ -55088,16 +55219,6 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
55088
55219
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
55089
55220
  kind: "mutation",
55090
55221
  auth: "admin"
55091
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
55092
- id: string(),
55093
- settings: record(string(), unknown()),
55094
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
55095
- secretKeys: array(string()).optional(),
55096
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
55097
- skipRestart: boolean().optional()
55098
- }), object({ success: boolean() }), {
55099
- kind: "mutation",
55100
- auth: "admin"
55101
55222
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
55102
55223
  addonId: string(),
55103
55224
  settings: record(string(), unknown())
@@ -57822,6 +57943,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
57822
57943
  }), {
57823
57944
  kind: "mutation",
57824
57945
  auth: "admin"
57946
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
57947
+ rows: number().int().nonnegative(),
57948
+ secrets: number().int().nonnegative()
57949
+ }), {
57950
+ kind: "mutation",
57951
+ auth: "admin"
57952
+ }), method(object({
57953
+ integrationId: string().min(1),
57954
+ patch: record(string(), unknown())
57955
+ }), object({ written: boolean() }), {
57956
+ kind: "mutation",
57957
+ auth: "admin"
57958
+ }), method(object({
57959
+ integrationId: string().min(1),
57960
+ keys: array(string().min(1))
57961
+ }), object({
57962
+ present: boolean(),
57963
+ removed: record(string(), unknown())
57964
+ }), {
57965
+ kind: "mutation",
57966
+ auth: "admin"
57825
57967
  });
57826
57968
  method(object({
57827
57969
  sourceUrl: string(),
@@ -77197,11 +77339,15 @@ discriminatedUnion("kind", [object({
77197
77339
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77198
77340
  * near F. A device that is not near one level most of the time has no floor.
77199
77341
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77200
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77201
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77342
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77343
+ * display waking): it is neither a run nor a pause. Among the remaining
77344
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77345
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77346
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77347
+ * is no run.
77202
77348
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77203
- * grid a person would type; stop dwell covers the longest pause; start dwell
77204
- * covers the longest standby blip above T.
77349
+ * grid a person would type; stop dwell covers the longest pause and the
77350
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
77205
77351
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77206
77352
  * run must hold exactly one true interval and nothing may flap outside.
77207
77353
  */
@@ -77212,6 +77358,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
77212
77358
  30 * SECOND_MS;
77213
77359
  60 * SECOND_MS;
77214
77360
  20 * MINUTE_MS$1;
77361
+ 90 * SECOND_MS;
77362
+ 30 * MINUTE_MS$1;
77363
+ 10 * MINUTE_MS$1;
77364
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
77215
77365
  10 * SECOND_MS;
77216
77366
  10 * SECOND_MS;
77217
77367
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80967,13 +81117,6 @@ Object.freeze({
80967
81117
  access: "view",
80968
81118
  role: "admin"
80969
81119
  },
80970
- "integrations.getSettings": {
80971
- capName: "integrations",
80972
- capScope: "system",
80973
- addonId: null,
80974
- access: "view",
80975
- role: "admin"
80976
- },
80977
81120
  "integrations.list": {
80978
81121
  capName: "integrations",
80979
81122
  capScope: "system",
@@ -80981,13 +81124,6 @@ Object.freeze({
80981
81124
  access: "view",
80982
81125
  role: "admin"
80983
81126
  },
80984
- "integrations.setSettings": {
80985
- capName: "integrations",
80986
- capScope: "system",
80987
- addonId: null,
80988
- access: "create",
80989
- role: "admin"
80990
- },
80991
81127
  "integrations.testConnection": {
80992
81128
  capName: "integrations",
80993
81129
  capScope: "system",
@@ -81982,6 +82118,13 @@ Object.freeze({
81982
82118
  access: "view",
81983
82119
  role: "admin"
81984
82120
  },
82121
+ "migrations.clearLegacyIntegrationRows": {
82122
+ capName: "migrations",
82123
+ capScope: "system",
82124
+ addonId: null,
82125
+ access: "delete",
82126
+ role: "admin"
82127
+ },
81985
82128
  "migrations.declareOwner": {
81986
82129
  capName: "migrations",
81987
82130
  capScope: "system",
@@ -81989,6 +82132,13 @@ Object.freeze({
81989
82132
  access: "create",
81990
82133
  role: "admin"
81991
82134
  },
82135
+ "migrations.deleteLegacyIntegrationRowKeys": {
82136
+ capName: "migrations",
82137
+ capScope: "system",
82138
+ addonId: null,
82139
+ access: "delete",
82140
+ role: "admin"
82141
+ },
81992
82142
  "migrations.dryRun": {
81993
82143
  capName: "migrations",
81994
82144
  capScope: "system",
@@ -82024,6 +82174,20 @@ Object.freeze({
82024
82174
  access: "create",
82025
82175
  role: "admin"
82026
82176
  },
82177
+ "migrations.patchLegacyIntegrationRows": {
82178
+ capName: "migrations",
82179
+ capScope: "system",
82180
+ addonId: null,
82181
+ access: "create",
82182
+ role: "admin"
82183
+ },
82184
+ "migrations.readLegacyIntegrationRows": {
82185
+ capName: "migrations",
82186
+ capScope: "system",
82187
+ addonId: null,
82188
+ access: "view",
82189
+ role: "admin"
82190
+ },
82027
82191
  "migrations.restorePreMigration": {
82028
82192
  capName: "migrations",
82029
82193
  capScope: "system",
@@ -92250,6 +92414,17 @@ object({
92250
92414
  delay: number().nonnegative().optional(),
92251
92415
  commands: record(string(), unknown())
92252
92416
  });
92417
+ //#endregion
92418
+ //#region src/custom-actions.ts
92419
+ /**
92420
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92421
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92422
+ * because it unpairs every controller of the bridge.
92423
+ */
92424
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92425
+ kind: "mutation",
92426
+ auth: "admin"
92427
+ }) });
92253
92428
  process.platform, process.env["SystemRoot"];
92254
92429
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
92255
92430
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -139149,14 +139324,60 @@ function clearPairingFiles(accessoryUuid, logger) {
139149
139324
  } });
139150
139325
  }
139151
139326
  }
139327
+ //#endregion
139328
+ //#region src/hap-instance-kinds.ts
139329
+ /**
139330
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139331
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139332
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139333
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139334
+ * (`hapPersistDirOf`). The default instance is keyed by the
139335
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139336
+ * controller that paired before keeps working.
139337
+ */
139338
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139339
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139340
+ /**
139341
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139342
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139343
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139344
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139345
+ */
139346
+ function instanceSalt(instanceId) {
139347
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139348
+ }
139349
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139350
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139351
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139352
+ function hapPersistDirOf(instanceId) {
139353
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139354
+ }
139355
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139356
+ title: "HomeKit bridge",
139357
+ nameField: "name",
139358
+ schema: object({
139359
+ name: string().min(1),
139360
+ username: string().min(1),
139361
+ uuid: string().min(1),
139362
+ pincode: string().min(1).meta({ secret: true }),
139363
+ enabled: boolean().optional()
139364
+ })
139365
+ });
139366
+ function identityOfBody(body) {
139367
+ return {
139368
+ username: body.username,
139369
+ uuid: body.uuid,
139370
+ pincode: body.pincode
139371
+ };
139372
+ }
139152
139373
  /** Deterministic and distinct from every device accessory uuid. */
139153
- function actionSwitchUuid(actionId) {
139154
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139374
+ function actionSwitchUuid(actionId, instanceId) {
139375
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
139155
139376
  }
139156
139377
  function buildActionSwitch(input) {
139157
139378
  const { actionId, displayName, run } = input;
139158
139379
  const autoOffMs = input.autoOffMs ?? 1e3;
139159
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139380
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
139160
139381
  accessory.category = import_dist.Categories.SWITCH;
139161
139382
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
139162
139383
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -139230,6 +139451,10 @@ var ActionExports = class {
139230
139451
  exposedAs: e.displayName
139231
139452
  }));
139232
139453
  }
139454
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139455
+ accessoryUuids() {
139456
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139457
+ }
139233
139458
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
139234
139459
  async attachAll() {
139235
139460
  for (const entry of this.entries) try {
@@ -139297,6 +139522,7 @@ var ActionExports = class {
139297
139522
  const mapper = buildActionSwitch({
139298
139523
  actionId: entry.actionId,
139299
139524
  displayName: entry.displayName,
139525
+ instanceId: this.ports.instanceId,
139300
139526
  run: async () => {
139301
139527
  await runExportedAction(this.ports.api, this.ports.logger, {
139302
139528
  exporter: EXPORTER,
@@ -139437,6 +139663,128 @@ var BridgeHost = class {
139437
139663
  }
139438
139664
  };
139439
139665
  //#endregion
139666
+ //#region src/mappers/kind.ts
139667
+ /**
139668
+ * Which orchestrator a device gets, which device types the picker offers, and
139669
+ * what a device's HomeKit accessory is called on the wire.
139670
+ *
139671
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139672
+ * import the uuid convention without importing the registry that imports them.
139673
+ */
139674
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139675
+ /**
139676
+ * The device types the Export picker offers, and the answer to the cap's
139677
+ * `listSupportedDeviceKinds`.
139678
+ *
139679
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139680
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139681
+ * doctrine the HA exporter writes down, and the thing that confined the
139682
+ * previous exporter to cameras when it was ignored.
139683
+ *
139684
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139685
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139686
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139687
+ * absent — each needs a service whose semantics the table cannot yet honour,
139688
+ * and offering the tab before the mapping exists is how an operator gets an
139689
+ * accessory that pairs and does nothing.
139690
+ *
139691
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139692
+ * (`builders/generic/security-system.ts`), and the two things the table could
139693
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139694
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139695
+ * refuses the write out loud instead of pretending to arm.
139696
+ */
139697
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139698
+ DeviceType.Camera,
139699
+ DeviceType.Light,
139700
+ DeviceType.Switch,
139701
+ DeviceType.Siren,
139702
+ DeviceType.Sensor,
139703
+ DeviceType.Lock,
139704
+ DeviceType.Presence,
139705
+ DeviceType.AlarmPanel,
139706
+ DeviceType.Generic
139707
+ ];
139708
+ /**
139709
+ * Resolve the orchestrator for a device from its TYPE.
139710
+ *
139711
+ * `null` means "no Export tab": the picker must not offer a type no
139712
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139713
+ * to `camera` — that is what every entry persisted before this function existed
139714
+ * carries, and a transient API failure must never re-shape an exposed camera.
139715
+ */
139716
+ function pickMapperKind(deviceType) {
139717
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139718
+ if (deviceType === DeviceType.Camera) return "camera";
139719
+ const withheld = applianceExport("homekit", deviceType);
139720
+ if (withheld !== null && !withheld.exported) return null;
139721
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139722
+ }
139723
+ /**
139724
+ * The deterministic HAP accessory UUID for a device.
139725
+ *
139726
+ * One function, because three call sites depend on the answer agreeing: the
139727
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139728
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139729
+ * and the export sync state that records it.
139730
+ *
139731
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139732
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139733
+ * would make every paired camera a stranger. Generic devices get their own
139734
+ * namespace so a switch and a camera that happen to share a device id are not
139735
+ * the same HomeKit accessory.
139736
+ */
139737
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139738
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139739
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139740
+ }
139741
+ //#endregion
139742
+ //#region src/bridge-instance.ts
139743
+ var BridgeInstance = class {
139744
+ id;
139745
+ name;
139746
+ identity;
139747
+ bridgeHost;
139748
+ exposure;
139749
+ /** The devices of this bridge that have a live accessory, by device id. */
139750
+ exposed = /* @__PURE__ */ new Map();
139751
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139752
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139753
+ actionExports = null;
139754
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139755
+ syncState = /* @__PURE__ */ new Map();
139756
+ constructor(id, name, identity, bridgeHost, exposure) {
139757
+ this.id = id;
139758
+ this.name = name;
139759
+ this.identity = identity;
139760
+ this.bridgeHost = bridgeHost;
139761
+ this.exposure = exposure;
139762
+ }
139763
+ get pincode() {
139764
+ return this.identity.pincode;
139765
+ }
139766
+ findEntry(deviceId) {
139767
+ const id = String(deviceId);
139768
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139769
+ }
139770
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139771
+ accessoryUuidOf(kind, deviceId) {
139772
+ return accessoryUuidFor(kind, deviceId, this.id);
139773
+ }
139774
+ /**
139775
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139776
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139777
+ */
139778
+ pairingUuids() {
139779
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139780
+ return [
139781
+ this.identity.uuid,
139782
+ ...fromDevices,
139783
+ ...this.actionExports?.accessoryUuids() ?? []
139784
+ ];
139785
+ }
139786
+ };
139787
+ //#endregion
139440
139788
  //#region src/exposed-entry.ts
139441
139789
  /**
139442
139790
  * Carrying an exposed-device entry across a re-expose.
@@ -139523,81 +139871,31 @@ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139523
139871
  /** The settings keys that moved into the record; the migrations name them. */
139524
139872
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139525
139873
  //#endregion
139526
- //#region src/hap-instance-kinds.ts
139527
- /**
139528
- * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139529
- * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139530
- * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139531
- * the row). The directory its pairing state lives in is derived from the id, never stored
139532
- * (`hapPersistDirOf`). The default instance is keyed by the
139533
- * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139534
- * controller that paired before keeps working.
139535
- */
139536
- /** The default instance keeps its record under the addon id (it adopted the old identity). */
139537
- var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139538
- /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139539
- var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139540
- /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139541
- function hapPersistDirOf(instanceId) {
139542
- return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139543
- }
139544
- var hapBridgesKind = defineEntryKind("hap-bridges", {
139545
- title: "HomeKit bridge",
139546
- nameField: "name",
139547
- schema: object({
139548
- name: string().min(1),
139549
- username: string().min(1),
139550
- uuid: string().min(1),
139551
- pincode: string().min(1).meta({ secret: true }),
139552
- enabled: boolean().optional()
139553
- })
139554
- });
139555
- function identityOfBody(body) {
139556
- return {
139557
- username: body.username,
139558
- uuid: body.uuid,
139559
- pincode: body.pincode
139560
- };
139561
- }
139562
- //#endregion
139563
139874
  //#region src/hap-identity.ts
139564
139875
  /**
139565
- * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139566
- * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139567
- * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139568
- * A legacy identity without a record means the migration did not finish, and minting then would
139569
- * unpair every controller, so the addon refuses to boot with the reason.
139876
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139877
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139878
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139879
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139880
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139881
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139882
+ *
139883
+ * Every other instance is read as it is stored; this module is only about the default one.
139570
139884
  */
139571
- /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139572
- async function resolveBridgeIdentity(fixedPin, ports) {
139885
+ async function resolveDefaultBridge(ports) {
139573
139886
  const stored = await ports.readRecord();
139574
139887
  if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139575
- if (stored.kind === "resolved") {
139576
- if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139577
- await ports.patchPincode(fixedPin);
139578
- return {
139579
- identity: identityOfBody({
139580
- ...stored.body,
139581
- pincode: fixedPin
139582
- }),
139583
- minted: false
139584
- };
139585
- }
139586
- return {
139587
- identity: identityOfBody(stored.body),
139588
- minted: false
139589
- };
139590
- }
139591
- if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139592
- const fresh = ports.mint();
139593
- const body = fixedPin === null ? fresh : {
139594
- ...fresh,
139595
- pincode: fixedPin
139888
+ if (stored.kind === "resolved") return {
139889
+ kind: "existing",
139890
+ identity: identityOfBody(stored.body)
139596
139891
  };
139892
+ 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");
139893
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139894
+ const body = ports.mint();
139597
139895
  await ports.putFresh(body);
139598
139896
  return {
139599
- identity: identityOfBody(body),
139600
- minted: true
139897
+ kind: "minted",
139898
+ identity: identityOfBody(body)
139601
139899
  };
139602
139900
  }
139603
139901
  //#endregion
@@ -139824,12 +140122,87 @@ function legacyIdentityOf(value) {
139824
140122
  };
139825
140123
  }
139826
140124
  //#endregion
140125
+ //#region src/migrations/bridge-name-to-instance.ts
140126
+ async function moveBridgeNameToInstance(ports) {
140127
+ const name = (await ports.readBridgeName()).trim();
140128
+ if (name === "") return {
140129
+ outcome: "already-done",
140130
+ summary: { renamed: false }
140131
+ };
140132
+ const held = await ports.readDefaultRecord();
140133
+ if (held === null || held.name === name) return {
140134
+ outcome: "already-done",
140135
+ summary: { renamed: false }
140136
+ };
140137
+ await ports.patchDefaultName(name);
140138
+ const after = await ports.readDefaultRecord();
140139
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140140
+ return {
140141
+ outcome: "done",
140142
+ summary: { renamed: true }
140143
+ };
140144
+ }
140145
+ //#endregion
140146
+ //#region src/migrations/drop-global-knobs.ts
140147
+ /**
140148
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140149
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140150
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140151
+ * fact of one node, which the node row carries since the per-node migration.
140152
+ *
140153
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140154
+ * keychain value would be orphaned otherwise):
140155
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140156
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140157
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140158
+ * can never lose the value. A `@<nodeId>` row is never touched.
140159
+ */
140160
+ async function clearFixedPin(ports) {
140161
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140162
+ outcome: "already-done",
140163
+ summary: { cleared: false }
140164
+ };
140165
+ await ports.clearFixedPin();
140166
+ return {
140167
+ outcome: "done",
140168
+ summary: { cleared: true }
140169
+ };
140170
+ }
140171
+ async function planDropGlobalKnobRows(addonId, ports) {
140172
+ const stored = await ports.readStored([
140173
+ "bridgeName",
140174
+ "fixedPin",
140175
+ "interfaceName",
140176
+ nodeKeyOf("interfaceName")
140177
+ ]);
140178
+ const present = [
140179
+ "bridgeName",
140180
+ "fixedPin",
140181
+ "interfaceName"
140182
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140183
+ if (present.length === 0) return { edits: [] };
140184
+ const rowId = (key) => `${addonId}.${key}`;
140185
+ return { edits: [{
140186
+ op: "deleteKeys",
140187
+ scope: ADDON_SETTINGS_TABLE,
140188
+ keys: present.map(rowId),
140189
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140190
+ addonId,
140191
+ key,
140192
+ value: stored[key]
140193
+ }])))
140194
+ }] };
140195
+ }
140196
+ //#endregion
139827
140197
  //#region src/migrations/index.ts
139828
140198
  var EXPORT_HAP_ID = "export-hap";
139829
140199
  var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139830
140200
  var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139831
140201
  var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139832
140202
  var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140203
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140204
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140205
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
139833
140206
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
139834
140207
  var ADDON_MIGRATIONS = [
139835
140208
  {
@@ -139898,7 +140271,7 @@ var ADDON_MIGRATIONS = [
139898
140271
  },
139899
140272
  {
139900
140273
  meta: {
139901
- id: "export-hap/2026-11-04-drop-exposure-keys",
140274
+ id: DROP_EXPOSURE_KEYS_ID,
139902
140275
  owner: EXPORT_HAP_ID,
139903
140276
  level: "addon-state",
139904
140277
  seq: 5,
@@ -139911,6 +140284,58 @@ var ADDON_MIGRATIONS = [
139911
140284
  fixtureMark: "the bridge name the migration does not know"
139912
140285
  },
139913
140286
  plan: planDropExposureKeys
140287
+ },
140288
+ {
140289
+ meta: {
140290
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140291
+ owner: EXPORT_HAP_ID,
140292
+ level: "addon-state",
140293
+ seq: 6,
140294
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140295
+ store: "settings",
140296
+ scope: "cluster",
140297
+ onFailure: "block-owner",
140298
+ bodyKind: "procedure",
140299
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140300
+ fixtureMark: "the bridge name the migration does not know"
140301
+ },
140302
+ procedure: moveBridgeNameToInstance
140303
+ },
140304
+ {
140305
+ meta: {
140306
+ id: DROP_GLOBAL_KNOBS_ID,
140307
+ owner: EXPORT_HAP_ID,
140308
+ level: "addon-state",
140309
+ seq: 7,
140310
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140311
+ store: "settings",
140312
+ scope: "cluster",
140313
+ onFailure: "tolerate",
140314
+ bodyKind: "procedure",
140315
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140316
+ fixtureMark: "the bridge name the migration does not know"
140317
+ },
140318
+ procedure: clearFixedPin
140319
+ },
140320
+ {
140321
+ meta: {
140322
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140323
+ owner: EXPORT_HAP_ID,
140324
+ level: "addon-state",
140325
+ seq: 8,
140326
+ dependsOn: [
140327
+ BRIDGE_NAME_TO_INSTANCE_ID,
140328
+ DROP_GLOBAL_KNOBS_ID,
140329
+ INTERFACE_NAME_PER_NODE_ID
140330
+ ],
140331
+ store: "settings",
140332
+ scope: "cluster",
140333
+ onFailure: "tolerate",
140334
+ bodyKind: "plan",
140335
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140336
+ fixtureMark: "the bridge name the migration does not know"
140337
+ },
140338
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
139914
140339
  }
139915
140340
  ];
139916
140341
  //#endregion
@@ -158005,81 +158430,6 @@ function errMsg$3(err) {
158005
158430
  return err instanceof Error ? err.message : String(err);
158006
158431
  }
158007
158432
  //#endregion
158008
- //#region src/mappers/kind.ts
158009
- /**
158010
- * Which orchestrator a device gets, which device types the picker offers, and
158011
- * what a device's HomeKit accessory is called on the wire.
158012
- *
158013
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
158014
- * import the uuid convention without importing the registry that imports them.
158015
- */
158016
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
158017
- /**
158018
- * The device types the Export picker offers, and the answer to the cap's
158019
- * `listSupportedDeviceKinds`.
158020
- *
158021
- * A UI FILTER, nothing more. Whether a device actually exports anything is
158022
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
158023
- * doctrine the HA exporter writes down, and the thing that confined the
158024
- * previous exporter to cameras when it was ignored.
158025
- *
158026
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
158027
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
158028
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
158029
- * absent — each needs a service whose semantics the table cannot yet honour,
158030
- * and offering the tab before the mapping exists is how an operator gets an
158031
- * accessory that pairs and does nothing.
158032
- *
158033
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
158034
- * (`builders/generic/security-system.ts`), and the two things the table could
158035
- * not previously honour are now honoured explicitly: HomeKit is only ever
158036
- * offered the arm modes the panel accepts, and a panel that requires a PIN
158037
- * refuses the write out loud instead of pretending to arm.
158038
- */
158039
- var HAP_EXPORTABLE_DEVICE_TYPES = [
158040
- DeviceType.Camera,
158041
- DeviceType.Light,
158042
- DeviceType.Switch,
158043
- DeviceType.Siren,
158044
- DeviceType.Sensor,
158045
- DeviceType.Lock,
158046
- DeviceType.Presence,
158047
- DeviceType.AlarmPanel,
158048
- DeviceType.Generic
158049
- ];
158050
- /**
158051
- * Resolve the orchestrator for a device from its TYPE.
158052
- *
158053
- * `null` means "no Export tab": the picker must not offer a type no
158054
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
158055
- * to `camera` — that is what every entry persisted before this function existed
158056
- * carries, and a transient API failure must never re-shape an exposed camera.
158057
- */
158058
- function pickMapperKind(deviceType) {
158059
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
158060
- if (deviceType === DeviceType.Camera) return "camera";
158061
- const withheld = applianceExport("homekit", deviceType);
158062
- if (withheld !== null && !withheld.exported) return null;
158063
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
158064
- }
158065
- /**
158066
- * The deterministic HAP accessory UUID for a device.
158067
- *
158068
- * One function, because three call sites depend on the answer agreeing: the
158069
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
158070
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
158071
- * and the export sync state that records it.
158072
- *
158073
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
158074
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
158075
- * would make every paired camera a stranger. Generic devices get their own
158076
- * namespace so a switch and a camera that happen to share a device id are not
158077
- * the same HomeKit accessory.
158078
- */
158079
- function accessoryUuidFor(kind, deviceId) {
158080
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
158081
- }
158082
- //#endregion
158083
158433
  //#region src/multi-tier/rtp-streaming-control.ts
158084
158434
  /**
158085
158435
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -158882,7 +159232,7 @@ async function buildCameraAccessory(input) {
158882
159232
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
158883
159233
  const isDoorbell = capNames.has("doorbell");
158884
159234
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
158885
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159235
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
158886
159236
  accessory.category = category;
158887
159237
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
158888
159238
  const bctx = {
@@ -159017,7 +159367,7 @@ async function buildGenericAccessory(input) {
159017
159367
  const rows = rowsForCaps(capNames);
159018
159368
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
159019
159369
  const deviceType = await resolveDeviceType(proxy);
159020
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159370
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
159021
159371
  accessory.category = accessoryCategoryFor(deviceType);
159022
159372
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
159023
159373
  const bctx = {
@@ -159250,8 +159600,6 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159250
159600
  }
159251
159601
  ];
159252
159602
  var DEFAULT_CONFIG = {
159253
- bridgeName: "CamStack Bridge",
159254
- fixedPin: "",
159255
159603
  interfaceName: "",
159256
159604
  clipRetentionDays: 14,
159257
159605
  exportSyncState: {}
@@ -159270,10 +159618,6 @@ var BANNED_PINCODES = new Set([
159270
159618
  "123-45-678",
159271
159619
  "876-54-321"
159272
159620
  ]);
159273
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
159274
- function isValidPincode(pin) {
159275
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
159276
- }
159277
159621
  function generateUsername() {
159278
159622
  const bytes = (0, node_crypto.randomBytes)(6);
159279
159623
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -159288,33 +159632,23 @@ function generatePincode() {
159288
159632
  }
159289
159633
  throw new Error("export-hap: failed to generate a non-trivial pincode");
159290
159634
  }
159635
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
159291
159636
  function buildBridgeUuid(bridgeName) {
159292
159637
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
159293
159638
  }
159294
159639
  var ExportHapAddon = class extends BaseAddon {
159295
159640
  /**
159296
- * The old `identity.pincode` secret: declared only so the identity migration can release its
159297
- * keychain entry when it clears the old setting. The identity itself is a record now.
159641
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159642
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159298
159643
  */
159299
- secretStatePaths = ["identity.pincode"];
159300
- exposed = /* @__PURE__ */ new Map();
159301
- /** The exported actions — switches beside the devices (D968). */
159302
- actionExports = null;
159644
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159645
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159646
+ bridges = /* @__PURE__ */ new Map();
159647
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159648
+ lifecycle = Promise.resolve();
159303
159649
  lastError;
159304
159650
  /** The HomeKit instances (D985): one record per bridge identity. */
159305
159651
  instances = null;
159306
- /**
159307
- * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159308
- * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159309
- * boot and written through on every change; this addon is the record's only writer.
159310
- */
159311
- exposure = {
159312
- name: HAP_EXPOSURE_NAME,
159313
- devices: [],
159314
- actions: []
159315
- };
159316
- /** Shared HAP setup code applied to every published accessory. */
159317
- pincode = "";
159318
159652
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
159319
159653
  bind;
159320
159654
  /**
@@ -159358,12 +159692,6 @@ var ExportHapAddon = class extends BaseAddon {
159358
159692
  hksvBuilds = new HksvBuildOutcomes();
159359
159693
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
159360
159694
  hksvClipPlanes = null;
159361
- /**
159362
- * THE bridge. Lazily created and published the first time a non-camera
159363
- * accessory needs it; never torn down while the addon runs, because an
159364
- * unpublish would drop a pairing the operator already entered a code for.
159365
- */
159366
- bridgeHost = null;
159367
159695
  constructor() {
159368
159696
  super({ ...DEFAULT_CONFIG });
159369
159697
  }
@@ -159377,31 +159705,24 @@ var ExportHapAddon = class extends BaseAddon {
159377
159705
  this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159378
159706
  description: {
159379
159707
  role: "services",
159380
- instanceMode: "single",
159708
+ instanceMode: "multiple",
159381
159709
  kind: "bridge",
159382
159710
  canTest: false
159383
159711
  },
159384
- formSchema: () => this.schema({ sections: [] }),
159712
+ formSchema: (id) => this.bridgeForm(id),
159385
159713
  initialBody: (name) => ({
159386
159714
  name,
159387
159715
  username: generateUsername(),
159388
159716
  uuid: buildBridgeUuid(name),
159389
159717
  pincode: generatePincode()
159390
159718
  }),
159391
- configured: (body) => body.username !== "" && body.pincode !== ""
159719
+ mintId: () => `hap-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
159720
+ configured: (body) => body.username !== "" && body.pincode !== "",
159721
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159392
159722
  });
159393
159723
  await this.migrateSettings();
159394
- const identity = await this.ensureIdentity();
159395
- await this.loadExposure();
159396
- this.pincode = identity.pincode;
159724
+ await this.ensureDefaultBridge();
159397
159725
  this.bind = this.config.interfaceName || void 0;
159398
- this.bridgeHost = new BridgeHost({
159399
- displayName: this.config.bridgeName,
159400
- uuid: identity.uuid,
159401
- pincode: identity.pincode,
159402
- bind: this.bind,
159403
- logger: this.ctx.logger
159404
- });
159405
159726
  try {
159406
159727
  await initHapStorage(node_path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
159407
159728
  } catch (err) {
@@ -159415,7 +159736,7 @@ var ExportHapAddon = class extends BaseAddon {
159415
159736
  this.hksvClipStore = new HksvClipStore({
159416
159737
  logger: this.ctx.logger.child("hksv-clips"),
159417
159738
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
159418
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159739
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159419
159740
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
159420
159741
  resolveFfmpeg: this.pinnedFfmpeg,
159421
159742
  spawnFn: node_child_process.spawn,
@@ -159428,161 +159749,323 @@ var ExportHapAddon = class extends BaseAddon {
159428
159749
  }) })
159429
159750
  });
159430
159751
  await this.serveHksvClipPlanes();
159752
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159753
+ for (const row of ordered) try {
159754
+ await this.startInstance(row.id);
159755
+ } catch (err) {
159756
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159757
+ instanceId: row.id,
159758
+ error: errMsg(err)
159759
+ } });
159760
+ }
159761
+ this.ctx.addDisposer(async () => {
159762
+ await this.enqueue(async () => {
159763
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159764
+ });
159765
+ });
159766
+ this.subscribeDeviceProvisionedForReconcile();
159767
+ this.subscribeDeviceReadyForReconcile();
159768
+ this.subscribeStorageLocationsForClips();
159769
+ const provider = this.buildExportProvider();
159770
+ const clipsProvider = createHksvVideoclipsProvider({
159771
+ logger: this.ctx.logger.child("hksv-clips"),
159772
+ addonId: EXPORT_HAP_ADDON_ID,
159773
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159774
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159775
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159776
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159777
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159778
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159779
+ });
159780
+ return {
159781
+ providers: [
159782
+ {
159783
+ capability: deviceExportCapability,
159784
+ provider
159785
+ },
159786
+ {
159787
+ capability: videoclipsCapability,
159788
+ provider: clipsProvider
159789
+ },
159790
+ {
159791
+ capability: integrationInstancesCapability,
159792
+ provider: this.requireInstances().toProvider()
159793
+ }
159794
+ ],
159795
+ customActions: exportHapActions,
159796
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159797
+ };
159798
+ }
159799
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159800
+ enqueue(job) {
159801
+ const run = this.lifecycle.then(job);
159802
+ this.lifecycle = run.then(() => void 0, () => void 0);
159803
+ return run;
159804
+ }
159805
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159806
+ instanceForDevice(deviceId) {
159807
+ const key = String(deviceId);
159808
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159809
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159810
+ }
159811
+ requireBridge(instanceId) {
159812
+ const inst = this.bridges.get(instanceId);
159813
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159814
+ return inst;
159815
+ }
159816
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159817
+ async startInstance(id) {
159818
+ await this.stopInstance(id);
159819
+ const resolved = await this.requireInstances().readResolved(id);
159820
+ if (resolved === null || !resolved.enabled) return;
159821
+ if (resolved.secrets === "unavailable") {
159822
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159823
+ return;
159824
+ }
159825
+ const identity = identityOfBody(resolved.body);
159826
+ const exposure = await this.loadExposure(id);
159827
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159828
+ displayName: resolved.body.name,
159829
+ uuid: identity.uuid,
159830
+ pincode: identity.pincode,
159831
+ bind: this.bind,
159832
+ logger: this.ctx.logger
159833
+ }), exposure);
159834
+ this.bridges.set(id, inst);
159835
+ this.warnOnDuplicateName(inst);
159431
159836
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
159432
- const cleaned = this.exposure.devices.filter((entry) => {
159837
+ const cleaned = inst.exposure.devices.filter((entry) => {
159433
159838
  if (validKinds.has(entry.mapperKind)) return true;
159434
159839
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
159435
159840
  return false;
159436
159841
  });
159437
- if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
159842
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
159438
159843
  for (const entry of cleaned) {
159439
159844
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
159440
159845
  try {
159441
- await this.attachMapper(entry);
159846
+ await this.attachMapper(inst, entry);
159442
159847
  const numericId = Number.parseInt(entry.deviceId, 10);
159443
159848
  if (Number.isFinite(numericId)) {
159444
- const fp = await this.computeExportFingerprint(numericId);
159445
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159849
+ const fp = await this.computeExportFingerprint(inst, numericId);
159850
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159446
159851
  }
159447
159852
  } catch (err) {
159448
159853
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
159449
159854
  }
159450
159855
  }
159451
- this.actionExports = new ActionExports({
159856
+ inst.actionExports = new ActionExports({
159452
159857
  api: this.ctx.api,
159453
159858
  logger: this.ctx.logger,
159859
+ instanceId: id,
159454
159860
  publish: async (accessory) => {
159455
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159861
+ if (await inst.bridgeHost.add(accessory)) return;
159456
159862
  await publishStandalone(accessory, {
159457
- pincode: this.pincode,
159863
+ pincode: inst.pincode,
159458
159864
  port: 0,
159459
159865
  bind: this.bind,
159460
159866
  logger: this.ctx.logger
159461
159867
  });
159462
159868
  },
159463
159869
  unpublish: async (accessory) => {
159464
- if (this.bridgeHost?.holds(accessory) === true) {
159465
- this.bridgeHost.remove(accessory);
159870
+ if (inst.bridgeHost.holds(accessory)) {
159871
+ inst.bridgeHost.remove(accessory);
159466
159872
  return;
159467
159873
  }
159468
159874
  await unpublishAccessory(accessory, this.ctx.logger);
159469
159875
  },
159470
- persist: (entries) => this.setExposedActions(entries)
159471
- }, this.exposure.actions);
159472
- await this.actionExports.attachAll();
159473
- await this.actionExports.reconcile();
159474
- this.ctx.addDisposer(async () => {
159475
- await this.actionExports?.dispose();
159476
- await this.detachAll();
159477
- await this.bridgeHost?.dispose();
159876
+ persist: (entries) => this.setExposedActions(inst, entries)
159877
+ }, inst.exposure.actions);
159878
+ await inst.actionExports.attachAll();
159879
+ await inst.actionExports.reconcile();
159880
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159881
+ instanceId: id,
159882
+ name: inst.name,
159883
+ devices: inst.exposed.size
159884
+ } });
159885
+ }
159886
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159887
+ async stopInstance(id) {
159888
+ const inst = this.bridges.get(id);
159889
+ if (inst === void 0) return;
159890
+ this.bridges.delete(id);
159891
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159892
+ inst.pendingRebuildTimers.clear();
159893
+ await inst.actionExports?.dispose();
159894
+ await this.detachAll(inst);
159895
+ await inst.bridgeHost.dispose();
159896
+ }
159897
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159898
+ async applyChange(id, change) {
159899
+ if (change === "deleted") {
159900
+ await this.removeInstance(id);
159901
+ return;
159902
+ }
159903
+ const resolved = await this.requireInstances().readResolved(id);
159904
+ if (resolved === null || !resolved.enabled) {
159905
+ await this.stopInstance(id);
159906
+ return;
159907
+ }
159908
+ const running = this.bridges.get(id);
159909
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159910
+ const next = identityOfBody(resolved.body);
159911
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159912
+ }
159913
+ await this.startInstance(id);
159914
+ }
159915
+ /**
159916
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159917
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159918
+ */
159919
+ async removeInstance(id) {
159920
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159921
+ await this.stopInstance(id);
159922
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159923
+ await this.exposureHandle().delete(id);
159924
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159925
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159926
+ }
159927
+ /**
159928
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159929
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159930
+ * devices stay.
159931
+ */
159932
+ regenerateBridge(instanceId) {
159933
+ return this.enqueue(async () => {
159934
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159935
+ await this.stopInstance(instanceId);
159936
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159937
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159938
+ await this.startInstance(instanceId);
159939
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159940
+ instanceId,
159941
+ accessories: uuids.length
159942
+ } });
159943
+ return { regenerated: true };
159478
159944
  });
159479
- this.subscribeDeviceProvisionedForReconcile();
159480
- this.subscribeDeviceReadyForReconcile();
159481
- this.subscribeStorageLocationsForClips();
159482
- this.disposeSharedRebuildTimers();
159483
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
159484
- const provider = {
159485
- getStatus: async (input) => {
159486
- ownInstance(statusInstanceOf(input));
159487
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
159488
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159489
- const setup = this.buildSetupBlock();
159490
- return {
159491
- linkState,
159492
- exposedDeviceCount: this.exposed.size,
159493
- ...this.lastError ? { error: this.lastError } : {},
159494
- ...setup ? { setup } : {}
159495
- };
159496
- },
159497
- listInstances: async () => [{
159498
- instanceId: EXPORT_HAP_ADDON_ID,
159499
- name: "HomeKit",
159500
- enabled: true,
159945
+ }
159946
+ warnOnDuplicateName(inst) {
159947
+ const key = inst.name.trim().toLowerCase();
159948
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159949
+ if (others.length === 0) return;
159950
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159951
+ instanceId: inst.id,
159952
+ name: inst.name,
159953
+ others: others.map((b) => b.id)
159954
+ } });
159955
+ }
159956
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159957
+ bridgeForm(id) {
159958
+ const inst = id === null ? void 0 : this.bridges.get(id);
159959
+ let qr = "";
159960
+ try {
159961
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159962
+ } catch (err) {
159963
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159964
+ instanceId: id,
159965
+ error: errMsg(err)
159966
+ } });
159967
+ }
159968
+ return this.schema({ sections: [{
159969
+ id: "bridge",
159970
+ title: "HomeKit bridge",
159971
+ 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.",
159972
+ fields: [...inst === void 0 ? [] : [{
159973
+ type: "info",
159974
+ key: "setupCode",
159975
+ label: "Setup code",
159976
+ content: inst.pincode
159977
+ }, ...qr === "" ? [] : [{
159978
+ type: "qr-code",
159979
+ key: "setupQr",
159980
+ label: "Pairing QR",
159981
+ caption: "Scan with the iOS Camera app.",
159982
+ value: qr,
159983
+ size: 192
159984
+ }]], ...id === null ? [] : [{
159985
+ type: "addon-action-button",
159986
+ key: "__regenerate-bridge",
159987
+ label: "Regenerate setup code",
159988
+ 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.",
159989
+ addonId: EXPORT_HAP_ADDON_ID,
159990
+ action: "regenerateBridge",
159991
+ buttonLabel: "Regenerate",
159992
+ variant: "danger",
159993
+ paramsStatic: { instanceId: id },
159994
+ 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."
159995
+ }]]
159996
+ }] });
159997
+ }
159998
+ /** Whole-addon status of the bridges: linked when any is paired. */
159999
+ statusOf(bridges) {
160000
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
160001
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
160002
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
160003
+ return {
160004
+ linkState,
160005
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
160006
+ ...this.lastError ? { error: this.lastError } : {},
160007
+ ...setup ? { setup } : {}
160008
+ };
160009
+ }
160010
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
160011
+ bridgesOf(instanceId) {
160012
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
160013
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
160014
+ }
160015
+ buildExportProvider() {
160016
+ return {
160017
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
160018
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
160019
+ instanceId: row.id,
160020
+ name: row.body.name,
160021
+ enabled: row.enabled,
159501
160022
  kind: "hap-bridge"
159502
- }],
160023
+ })),
159503
160024
  listSupportedDeviceKinds: async ({ instanceId }) => {
159504
- ownInstance(instanceId);
160025
+ this.bridgesOf(instanceId);
159505
160026
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
159506
160027
  },
159507
- listExposedDevices: async ({ instanceId }) => {
159508
- ownInstance(instanceId);
159509
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159510
- const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159511
- return {
159512
- deviceId,
159513
- exposedAs: m.accessory.displayName,
159514
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159515
- };
159516
- });
159517
- },
159518
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159519
- ownInstance(instanceId);
159520
- return this.exposeDevice(deviceId, capabilities);
159521
- },
159522
- unexposeDevice: async ({ instanceId, deviceId }) => {
159523
- ownInstance(instanceId);
159524
- return this.unexposeDevice(deviceId);
159525
- },
160028
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
160029
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
160030
+ return {
160031
+ deviceId,
160032
+ exposedAs: m.accessory.displayName,
160033
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
160034
+ };
160035
+ })),
160036
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
160037
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
159526
160038
  listSupportedEntityKinds: async () => ["device", "action"],
159527
160039
  listExposedEntities: async ({ instanceId }) => {
159528
- ownInstance(instanceId);
159529
- await this.actionExports?.reconcile();
159530
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
159531
- entity: {
159532
- kind: "device",
159533
- deviceId
159534
- },
159535
- exposedAs: m.accessory.displayName
159536
- })), ...this.actionExports?.list() ?? []];
160040
+ const out = [];
160041
+ for (const inst of this.bridgesOf(instanceId)) {
160042
+ await inst.actionExports?.reconcile();
160043
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
160044
+ entity: {
160045
+ kind: "device",
160046
+ deviceId
160047
+ },
160048
+ exposedAs: m.accessory.displayName
160049
+ })), ...inst.actionExports?.list() ?? []);
160050
+ }
160051
+ return out;
159537
160052
  },
159538
160053
  exposeEntity: async ({ instanceId, entity }) => {
159539
- ownInstance(instanceId);
159540
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
159541
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
160054
+ const inst = this.requireBridge(instanceId);
160055
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
160056
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
159542
160057
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159543
160058
  },
159544
160059
  unexposeEntity: async ({ instanceId, entity }) => {
159545
- ownInstance(instanceId);
159546
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
159547
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
160060
+ const inst = this.requireBridge(instanceId);
160061
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
160062
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
159548
160063
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159549
160064
  },
159550
160065
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
159551
160066
  getDeviceLiveContribution: async () => null,
159552
160067
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
159553
160068
  };
159554
- const clipsProvider = createHksvVideoclipsProvider({
159555
- logger: this.ctx.logger.child("hksv-clips"),
159556
- addonId: EXPORT_HAP_ADDON_ID,
159557
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
159558
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159559
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159560
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159561
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159562
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159563
- });
159564
- return [
159565
- {
159566
- capability: deviceExportCapability,
159567
- provider
159568
- },
159569
- {
159570
- capability: videoclipsCapability,
159571
- provider: clipsProvider
159572
- },
159573
- {
159574
- capability: integrationInstancesCapability,
159575
- provider: this.requireInstances().toProvider()
159576
- }
159577
- ];
159578
- }
159579
- async onConfigChanged() {
159580
- const fixedPin = this.config.fixedPin;
159581
- if (!fixedPin || !isValidPincode(fixedPin)) return;
159582
- const handle = this.requireRecords().kind(hapBridgesKind);
159583
- const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159584
- if (row === null || row.data.pincode === fixedPin) return;
159585
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159586
160069
  }
159587
160070
  requireInstances() {
159588
160071
  if (this.instances === null) throw new Error("export-hap: instances are not initialised");
@@ -159616,13 +160099,17 @@ var ExportHapAddon = class extends BaseAddon {
159616
160099
  }
159617
160100
  return "created";
159618
160101
  },
159619
- readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
160102
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
160103
+ patchDefaultName: async (name) => {
160104
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
160105
+ },
160106
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
159620
160107
  };
159621
160108
  }
159622
- /** The identity of the default instance; see `resolveBridgeIdentity`. */
159623
- async ensureIdentity() {
160109
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
160110
+ async ensureDefaultBridge() {
159624
160111
  const handle = this.requireRecords().kind(hapBridgesKind);
159625
- const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
160112
+ const boot = await resolveDefaultBridge({
159626
160113
  readRecord: async () => {
159627
160114
  const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159628
160115
  if (resolved === null) return { kind: "absent" };
@@ -159632,9 +160119,7 @@ var ExportHapAddon = class extends BaseAddon {
159632
160119
  } : { kind: "unavailable" };
159633
160120
  },
159634
160121
  legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159635
- patchPincode: async (pincode) => {
159636
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159637
- },
160122
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
159638
160123
  putFresh: async (body) => {
159639
160124
  await handle.put({
159640
160125
  id: HAP_DEFAULT_INSTANCE_ID,
@@ -159642,14 +160127,13 @@ var ExportHapAddon = class extends BaseAddon {
159642
160127
  }, { ifRev: 0 });
159643
160128
  },
159644
160129
  mint: () => ({
159645
- name: this.config.bridgeName,
160130
+ name: DEFAULT_BRIDGE_NAME,
159646
160131
  username: generateUsername(),
159647
- uuid: buildBridgeUuid(this.config.bridgeName),
160132
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
159648
160133
  pincode: generatePincode()
159649
160134
  })
159650
160135
  });
159651
- if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159652
- return identity;
160136
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
159653
160137
  }
159654
160138
  /**
159655
160139
  * Build the generic `device-export` `setup` block surfaced via
@@ -159658,10 +160142,10 @@ var ExportHapAddon = class extends BaseAddon {
159658
160142
  * a copyable field, and a short pairing instruction. Returns `null`
159659
160143
  * until the bridge has booted and produced both values.
159660
160144
  */
159661
- buildSetupBlock() {
159662
- const setupCode = this.pincode;
160145
+ buildSetupBlock(inst) {
160146
+ const setupCode = inst.pincode;
159663
160147
  if (!setupCode) return null;
159664
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160148
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
159665
160149
  return {
159666
160150
  ...qr !== void 0 ? { qr } : {},
159667
160151
  fields: [{
@@ -159682,18 +160166,18 @@ var ExportHapAddon = class extends BaseAddon {
159682
160166
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
159683
160167
  * still said `streamPreference=auto`.
159684
160168
  */
159685
- async exposeDevice(deviceId, capabilities, settings) {
160169
+ async exposeDevice(inst, deviceId, capabilities, settings) {
159686
160170
  const numericId = Number.parseInt(deviceId, 10);
159687
160171
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159688
- if (this.exposed.has(deviceId)) {
160172
+ if (inst.exposed.has(deviceId)) {
159689
160173
  log.debug("export-hap: device already exposed — refreshing capabilities");
159690
- await this.detachMapper(deviceId);
160174
+ await this.detachMapper(inst, deviceId);
159691
160175
  }
159692
160176
  const summary = await this.fetchDeviceSummary(numericId);
159693
160177
  const mapperKind = pickMapperKind(summary?.type);
159694
160178
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
159695
160179
  const displayName = summary?.name ?? `Device ${deviceId}`;
159696
- const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
160180
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159697
160181
  const rebuilt = {
159698
160182
  deviceId,
159699
160183
  displayName,
@@ -159705,37 +160189,38 @@ var ExportHapAddon = class extends BaseAddon {
159705
160189
  ...rebuilt,
159706
160190
  settings
159707
160191
  }, previous, ["settings", "capabilities"]);
159708
- const attached = await this.attachMapper(baseEntry);
160192
+ const attached = await this.attachMapper(inst, baseEntry);
159709
160193
  const finalEntry = {
159710
160194
  ...baseEntry,
159711
160195
  childAccessoryUuids: attached.childAccessoryUuids
159712
160196
  };
159713
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
160197
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
159714
160198
  next.push(finalEntry);
159715
- await this.setExposedDevices(next);
160199
+ await this.setExposedDevices(inst, next);
159716
160200
  if (Number.isFinite(numericId)) {
159717
- const fp = await this.computeExportFingerprint(numericId);
159718
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160201
+ const fp = await this.computeExportFingerprint(inst, numericId);
160202
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159719
160203
  }
159720
160204
  log.info("export-hap: exposed device", { meta: {
160205
+ instanceId: inst.id,
159721
160206
  displayName,
159722
160207
  mapperKind,
159723
160208
  childCount: attached.childAccessoryUuids.length
159724
160209
  } });
159725
160210
  }
159726
- async unexposeDevice(deviceId, options = {}) {
160211
+ async unexposeDevice(inst, deviceId, options = {}) {
159727
160212
  const numericId = Number.parseInt(deviceId, 10);
159728
160213
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159729
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
159730
- await this.detachMapper(deviceId);
159731
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159732
- if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
159733
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
159734
- await this.forgetFingerprint(numericId);
160214
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160215
+ await this.detachMapper(inst, deviceId);
160216
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160217
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160218
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160219
+ await this.forgetFingerprint(inst, numericId);
159735
160220
  this.hksvBuilds.forget(numericId);
159736
- log.info("export-hap: unexposed device");
160221
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
159737
160222
  }
159738
- async attachMapper(entry) {
160223
+ async attachMapper(inst, entry) {
159739
160224
  const factory = getMapperFactory(entry.mapperKind);
159740
160225
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
159741
160226
  const mapper = await factory({
@@ -159743,6 +160228,7 @@ var ExportHapAddon = class extends BaseAddon {
159743
160228
  deviceId: entry.deviceId,
159744
160229
  displayName: entry.displayName,
159745
160230
  options: {
160231
+ instanceId: inst.id,
159746
160232
  decodeMemos: this.decodeMemos,
159747
160233
  resolveFfmpeg: this.pinnedFfmpeg,
159748
160234
  hksvClipStore: this.hksvClipStore,
@@ -159762,29 +160248,29 @@ var ExportHapAddon = class extends BaseAddon {
159762
160248
  useBridge: entry.settings?.useBridge
159763
160249
  });
159764
160250
  for (const accessory of mapper.accessories) {
159765
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160251
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
159766
160252
  await publishStandalone(accessory, {
159767
- pincode: this.pincode,
160253
+ pincode: inst.pincode,
159768
160254
  port: 0,
159769
160255
  bind: this.bind,
159770
160256
  logger: this.ctx.logger
159771
160257
  });
159772
160258
  }
159773
- this.exposed.set(entry.deviceId, mapper);
160259
+ inst.exposed.set(entry.deviceId, mapper);
159774
160260
  return { childAccessoryUuids: [] };
159775
160261
  }
159776
- async detachMapper(deviceId) {
159777
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160262
+ async detachMapper(inst, deviceId) {
160263
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
159778
160264
  if (pendingTimer) {
159779
160265
  clearTimeout(pendingTimer);
159780
- this.pendingRebuildTimers.delete(deviceId);
160266
+ inst.pendingRebuildTimers.delete(deviceId);
159781
160267
  }
159782
- const mapper = this.exposed.get(deviceId);
160268
+ const mapper = inst.exposed.get(deviceId);
159783
160269
  if (!mapper) return;
159784
- this.exposed.delete(deviceId);
160270
+ inst.exposed.delete(deviceId);
159785
160271
  for (const accessory of mapper.accessories) {
159786
- if (this.bridgeHost?.holds(accessory) === true) {
159787
- this.bridgeHost.remove(accessory);
160272
+ if (inst.bridgeHost.holds(accessory)) {
160273
+ inst.bridgeHost.remove(accessory);
159788
160274
  continue;
159789
160275
  }
159790
160276
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -159793,21 +160279,22 @@ var ExportHapAddon = class extends BaseAddon {
159793
160279
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
159794
160280
  });
159795
160281
  }
159796
- requireActionExports() {
159797
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
159798
- return this.actionExports;
160282
+ requireActionExports(inst) {
160283
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160284
+ return inst.actionExports;
159799
160285
  }
159800
- async detachAll() {
159801
- const ids = Array.from(this.exposed.keys());
159802
- for (const id of ids) await this.detachMapper(id);
160286
+ async detachAll(inst) {
160287
+ const ids = Array.from(inst.exposed.keys());
160288
+ for (const id of ids) await this.detachMapper(inst, id);
159803
160289
  }
159804
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
159805
- * on detach so stale timers can't republish a removed accessory. */
159806
- pendingRebuildTimers = /* @__PURE__ */ new Map();
159807
160290
  /** Deterministic HAP accessory UUID for a device — the same one the
159808
160291
  * orchestrator built it with (`mappers/kind.ts`). */
159809
- hapAccessoryUuid(deviceId) {
159810
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160292
+ hapAccessoryUuid(inst, deviceId) {
160293
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160294
+ }
160295
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160296
+ syncStateOf(inst) {
160297
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
159811
160298
  }
159812
160299
  /**
159813
160300
  * Export fingerprint of a device from its PERSISTED features + type
@@ -159825,7 +160312,7 @@ var ExportHapAddon = class extends BaseAddon {
159825
160312
  * A brand-new un-probed device with no persisted entry falls back to its
159826
160313
  * fresh fingerprint (publishes once, acceptable).
159827
160314
  */
159828
- async computeExportFingerprint(deviceId) {
160315
+ async computeExportFingerprint(inst, deviceId) {
159829
160316
  try {
159830
160317
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
159831
160318
  if (!device) return null;
@@ -159834,10 +160321,10 @@ var ExportHapAddon = class extends BaseAddon {
159834
160321
  deviceType: device.type,
159835
160322
  features: device.features
159836
160323
  });
159837
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160324
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
159838
160325
  const withToken = withRecordabilityToken({
159839
160326
  base: fresh,
159840
- token: await this.readRecordabilityToken(deviceId, device.type),
160327
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
159841
160328
  persisted
159842
160329
  });
159843
160330
  return resolveExportFingerprint({
@@ -159857,12 +160344,12 @@ var ExportHapAddon = class extends BaseAddon {
159857
160344
  * republish every non-camera accessory once for nothing) and for a camera
159858
160345
  * whose profiles could not be read right now.
159859
160346
  */
159860
- async readRecordabilityToken(deviceId, type) {
160347
+ async readRecordabilityToken(inst, deviceId, type) {
159861
160348
  if (pickMapperKind(type) !== "camera") return null;
159862
160349
  try {
159863
160350
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
159864
160351
  return recordabilityTokenFor({
159865
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160352
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
159866
160353
  entries: entries ?? null
159867
160354
  });
159868
160355
  } catch {
@@ -159871,20 +160358,20 @@ var ExportHapAddon = class extends BaseAddon {
159871
160358
  }
159872
160359
  /** Persist a device's current export fingerprint into `exportSyncState`
159873
160360
  * (best-effort; called after a successful attach). */
159874
- async persistFingerprint(deviceId, fingerprint) {
159875
- const state = syncStateFromJson(this.config.exportSyncState);
160361
+ async persistFingerprint(inst, deviceId, fingerprint) {
160362
+ const state = this.syncStateOf(inst);
159876
160363
  state.set(deviceId, {
159877
160364
  fingerprint,
159878
- externalIds: [this.hapAccessoryUuid(deviceId)]
160365
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
159879
160366
  });
159880
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160367
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159881
160368
  }
159882
160369
  /** Drop a device's `exportSyncState` entry (on unexpose). */
159883
- async forgetFingerprint(deviceId) {
159884
- const state = syncStateFromJson(this.config.exportSyncState);
160370
+ async forgetFingerprint(inst, deviceId) {
160371
+ const state = this.syncStateOf(inst);
159885
160372
  if (!state.has(deviceId)) return;
159886
160373
  state.delete(deviceId);
159887
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160374
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159888
160375
  }
159889
160376
  /**
159890
160377
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -159915,34 +160402,23 @@ var ExportHapAddon = class extends BaseAddon {
159915
160402
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
159916
160403
  if (deviceIdNumeric === null) return;
159917
160404
  const deviceId = String(deviceIdNumeric);
159918
- if (!this.findEntry(deviceIdNumeric)) return;
159919
- const existing = this.pendingRebuildTimers.get(deviceId);
159920
- if (existing) clearTimeout(existing);
159921
- const timer = setTimeout(() => {
159922
- this.pendingRebuildTimers.delete(deviceId);
159923
- this.reconcileDevice(deviceId);
159924
- }, 500);
159925
- if (typeof timer.unref === "function") timer.unref();
159926
- this.pendingRebuildTimers.set(deviceId, timer);
160405
+ for (const inst of this.bridges.values()) {
160406
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160407
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160408
+ if (existing) clearTimeout(existing);
160409
+ const timer = setTimeout(() => {
160410
+ inst.pendingRebuildTimers.delete(deviceId);
160411
+ this.reconcileDevice(inst, deviceId);
160412
+ }, 500);
160413
+ if (typeof timer.unref === "function") timer.unref();
160414
+ inst.pendingRebuildTimers.set(deviceId, timer);
160415
+ }
159927
160416
  });
159928
160417
  this.ctx.addDisposer(async () => {
159929
160418
  unsubscribe();
159930
160419
  });
159931
160420
  }
159932
160421
  /**
159933
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
159934
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
159935
- * per-device timers into `pendingRebuildTimers` but never clear the map on
159936
- * their own teardown — that shared resource is cleared here, exactly once, on
159937
- * shutdown.
159938
- */
159939
- disposeSharedRebuildTimers() {
159940
- this.ctx.addDisposer(async () => {
159941
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
159942
- this.pendingRebuildTimers.clear();
159943
- });
159944
- }
159945
- /**
159946
160422
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
159947
160423
  * its persisted export shape changes. `DeviceProvisioned` is gated by
159948
160424
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -159972,22 +160448,22 @@ var ExportHapAddon = class extends BaseAddon {
159972
160448
  * Errors are logged and swallowed — a failed reconcile leaves the prior
159973
160449
  * accessory up, which is strictly better than removing it.
159974
160450
  */
159975
- async reconcileDevice(deviceId) {
160451
+ async reconcileDevice(inst, deviceId) {
159976
160452
  const numericId = Number.parseInt(deviceId, 10);
159977
160453
  if (!Number.isFinite(numericId)) return;
159978
- const entry = this.findEntry(numericId);
160454
+ const entry = inst.findEntry(numericId);
159979
160455
  if (!entry) return;
159980
160456
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159981
- const current = await this.computeExportFingerprint(numericId);
160457
+ const current = await this.computeExportFingerprint(inst, numericId);
159982
160458
  if (current === null) {
159983
160459
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
159984
160460
  return;
159985
160461
  }
159986
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160462
+ const last = this.syncStateOf(inst).get(numericId);
159987
160463
  if (last?.fingerprint === current) {
159988
- if (!this.exposed.has(deviceId)) try {
159989
- await this.attachMapper(entry);
159990
- await this.persistFingerprint(numericId, current);
160464
+ if (!inst.exposed.has(deviceId)) try {
160465
+ await this.attachMapper(inst, entry);
160466
+ await this.persistFingerprint(inst, numericId, current);
159991
160467
  } catch (err) {
159992
160468
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
159993
160469
  }
@@ -159999,9 +160475,9 @@ var ExportHapAddon = class extends BaseAddon {
159999
160475
  to: current.slice(0, 12)
160000
160476
  } });
160001
160477
  try {
160002
- await this.detachMapper(deviceId);
160003
- await this.attachMapper(entry);
160004
- await this.persistFingerprint(numericId, current);
160478
+ await this.detachMapper(inst, deviceId);
160479
+ await this.attachMapper(inst, entry);
160480
+ await this.persistFingerprint(inst, numericId, current);
160005
160481
  } catch (err) {
160006
160482
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
160007
160483
  }
@@ -160064,7 +160540,7 @@ var ExportHapAddon = class extends BaseAddon {
160064
160540
  return null;
160065
160541
  }
160066
160542
  }
160067
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160543
+ /** The one declaration of the bind-interface field: a fact of one node. */
160068
160544
  interfaceNameField() {
160069
160545
  return this.field({
160070
160546
  type: "text",
@@ -160084,10 +160560,26 @@ var ExportHapAddon = class extends BaseAddon {
160084
160560
  fields: [this.interfaceNameField()]
160085
160561
  }] }) : null;
160086
160562
  }
160563
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160564
+ async deviceDefaultsSchema(cap) {
160565
+ return cap === "device-export" ? this.schema({ sections: [{
160566
+ id: "export-hap-defaults",
160567
+ title: "HomeKit Export",
160568
+ fields: [this.field({
160569
+ type: "number",
160570
+ key: "clipRetentionDays",
160571
+ label: "Keep HomeKit clips for (days)",
160572
+ 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.",
160573
+ default: DEFAULT_CONFIG.clipRetentionDays,
160574
+ placement: { tab: "advanced" }
160575
+ })]
160576
+ }] }) : null;
160577
+ }
160087
160578
  /**
160088
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
160089
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
160090
- * value the migration wrote.
160579
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160580
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160581
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160582
+ * config when anything landed, so this boot binds the value the migration wrote.
160091
160583
  */
160092
160584
  async migrateSettings() {
160093
160585
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
@@ -160097,47 +160589,15 @@ var ExportHapAddon = class extends BaseAddon {
160097
160589
  ...this.exposureMigrationPorts()
160098
160590
  }))).applied.length > 0) await this.resolveConfig();
160099
160591
  }
160100
- globalSettingsSchema() {
160101
- return this.schema({ sections: [{
160102
- id: "export-hap",
160103
- title: "HomeKit Export",
160104
- 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.",
160105
- columns: 1,
160106
- fields: [
160107
- this.field({
160108
- type: "text",
160109
- key: "bridgeName",
160110
- label: "Installation name",
160111
- 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.",
160112
- default: DEFAULT_CONFIG.bridgeName,
160113
- requiresRestart: true,
160114
- placement: { tab: "advanced" }
160115
- }),
160116
- this.field({
160117
- type: "password",
160118
- key: "fixedPin",
160119
- label: "Fixed setup code (XXX-XX-XXX)",
160120
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
160121
- default: DEFAULT_CONFIG.fixedPin,
160122
- requiresRestart: true,
160123
- placement: { tab: "advanced" }
160124
- }),
160125
- this.interfaceNameField(),
160126
- this.field({
160127
- type: "number",
160128
- key: "clipRetentionDays",
160129
- label: "Keep HomeKit clips for (days)",
160130
- 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.",
160131
- default: DEFAULT_CONFIG.clipRetentionDays,
160132
- placement: { tab: "advanced" }
160133
- })
160134
- ]
160135
- }] });
160592
+ scopedSettingsCapabilities() {
160593
+ return ["device-export"];
160136
160594
  }
160137
160595
  async buildDeviceSettingsContribution(deviceId) {
160138
160596
  const kind = await this.resolveExportKind(deviceId);
160139
160597
  if (kind === null) return null;
160140
- const entry = this.findEntry(deviceId);
160598
+ const inst = this.instanceForDevice(deviceId);
160599
+ if (inst === null) return null;
160600
+ const entry = inst.findEntry(deviceId);
160141
160601
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
160142
160602
  const enabled = entry !== null;
160143
160603
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -160147,13 +160607,13 @@ var ExportHapAddon = class extends BaseAddon {
160147
160607
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
160148
160608
  const keepClipsKey = `hap:${deviceId}:keepClips`;
160149
160609
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
160150
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160610
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
160151
160611
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
160152
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160612
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
160153
160613
  const name = entry?.displayName ?? `Device ${deviceId}`;
160154
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
160155
- const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.pincode}.`;
160156
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160614
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160615
+ 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}.`;
160616
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
160157
160617
  let qrValue = "";
160158
160618
  if (qrSource) try {
160159
160619
  qrValue = qrSource.setupURI();
@@ -160195,7 +160655,7 @@ var ExportHapAddon = class extends BaseAddon {
160195
160655
  type: "info",
160196
160656
  key: `hap:${deviceId}:hksvRecordingStatus`,
160197
160657
  label: "HomeKit recording (Secure Video)",
160198
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160658
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160199
160659
  showWhen: {
160200
160660
  field: enabledKey,
160201
160661
  equals: true
@@ -160279,7 +160739,7 @@ var ExportHapAddon = class extends BaseAddon {
160279
160739
  type: "qr-code",
160280
160740
  key: "__hap-pair-qr",
160281
160741
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
160282
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.pincode}.`,
160742
+ 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}.`,
160283
160743
  value: qrValue,
160284
160744
  size: 192,
160285
160745
  alt: `HomeKit pairing QR for ${name}`,
@@ -160318,8 +160778,10 @@ var ExportHapAddon = class extends BaseAddon {
160318
160778
  async applyDeviceSettingsPatch(deviceId, patch) {
160319
160779
  const deviceIdStr = String(deviceId);
160320
160780
  const log = this.ctx.logger.withTags({ deviceId });
160321
- const current = this.findEntry(deviceId);
160322
- const wasEnabled = this.exposed.has(deviceIdStr);
160781
+ const inst = this.instanceForDevice(deviceId);
160782
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160783
+ const current = inst.findEntry(deviceId);
160784
+ const wasEnabled = inst.exposed.has(deviceIdStr);
160323
160785
  const enabledKey = `hap:${deviceId}:enabled`;
160324
160786
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
160325
160787
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -160348,12 +160810,12 @@ var ExportHapAddon = class extends BaseAddon {
160348
160810
  clipRetentionDays
160349
160811
  };
160350
160812
  if (!enabledValue) {
160351
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160813
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
160352
160814
  return { success: true };
160353
160815
  }
160354
160816
  if (!wasEnabled) {
160355
- await this.exposeDevice(deviceIdStr);
160356
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160817
+ await this.exposeDevice(inst, deviceIdStr);
160818
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160357
160819
  return { success: true };
160358
160820
  }
160359
160821
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -160367,7 +160829,7 @@ var ExportHapAddon = class extends BaseAddon {
160367
160829
  mapperKind,
160368
160830
  useBridge
160369
160831
  });
160370
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160832
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160371
160833
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
160372
160834
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
160373
160835
  streamPreference: {
@@ -160384,8 +160846,8 @@ var ExportHapAddon = class extends BaseAddon {
160384
160846
  }
160385
160847
  } });
160386
160848
  try {
160387
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
160388
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160849
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160850
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
160389
160851
  } catch (err) {
160390
160852
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
160391
160853
  }
@@ -160447,35 +160909,38 @@ var ExportHapAddon = class extends BaseAddon {
160447
160909
  exposureHandle() {
160448
160910
  return this.requireRecords().kind(hapBridgeExportsKind);
160449
160911
  }
160450
- /** Load the default instance's exposure record; create it empty when none exists. */
160451
- async loadExposure() {
160912
+ /** Load a bridge's exposure record; create it empty when none exists. */
160913
+ async loadExposure(id) {
160452
160914
  const handle = this.exposureHandle();
160453
- const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160454
- if (row !== null) {
160455
- this.exposure = row.data;
160456
- return;
160457
- }
160915
+ const row = await handle.get(id);
160916
+ if (row !== null) return row.data;
160917
+ const empty = {
160918
+ name: HAP_EXPOSURE_NAME,
160919
+ devices: [],
160920
+ actions: []
160921
+ };
160458
160922
  await handle.put({
160459
- id: HAP_DEFAULT_INSTANCE_ID,
160460
- data: this.exposure
160923
+ id,
160924
+ data: empty
160461
160925
  }, { ifRev: 0 });
160926
+ return empty;
160462
160927
  }
160463
- async writeExposure(next) {
160928
+ async writeExposure(inst, next) {
160464
160929
  await this.exposureHandle().put({
160465
- id: HAP_DEFAULT_INSTANCE_ID,
160930
+ id: inst.id,
160466
160931
  data: next
160467
160932
  });
160468
- this.exposure = next;
160933
+ inst.exposure = next;
160469
160934
  }
160470
- setExposedDevices(devices) {
160471
- return this.writeExposure({
160472
- ...this.exposure,
160935
+ setExposedDevices(inst, devices) {
160936
+ return this.writeExposure(inst, {
160937
+ ...inst.exposure,
160473
160938
  devices
160474
160939
  });
160475
160940
  }
160476
- setExposedActions(actions) {
160477
- return this.writeExposure({
160478
- ...this.exposure,
160941
+ setExposedActions(inst, actions) {
160942
+ return this.writeExposure(inst, {
160943
+ ...inst.exposure,
160479
160944
  actions
160480
160945
  });
160481
160946
  }
@@ -160499,16 +160964,12 @@ var ExportHapAddon = class extends BaseAddon {
160499
160964
  readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160500
160965
  };
160501
160966
  }
160502
- findEntry(deviceId) {
160503
- const id = String(deviceId);
160504
- return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
160505
- }
160506
- async updateEntrySettings(deviceIdStr, settings) {
160507
- const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160967
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160968
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160508
160969
  ...e,
160509
160970
  settings
160510
160971
  } : e);
160511
- await this.setExposedDevices(next);
160972
+ await this.setExposedDevices(inst, next);
160512
160973
  }
160513
160974
  };
160514
160975
  function errMsg(err) {
@@ -160523,6 +160984,7 @@ exports.default = ExportHapAddon;
160523
160984
  exports.__toCommonJS = __toCommonJS;
160524
160985
  exports.deriveUsername = deriveUsername;
160525
160986
  exports.describeHksvCamera = describeHksvCamera;
160987
+ exports.exportHapActions = exportHapActions;
160526
160988
  exports.initHapStorage = initHapStorage;
160527
160989
  exports.publishStandalone = publishStandalone;
160528
160990
  exports.resolveClipRetentionDays = resolveClipRetentionDays;