@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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
- import { spawn } from "node:child_process";
3
2
  import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { spawn } from "node:child_process";
4
4
  import * as path from "node:path";
5
5
  import { join } from "node:path";
6
6
  import { createReadStream, createWriteStream, readFileSync } from "node:fs";
@@ -6021,7 +6021,7 @@ var ZodIssueCode = {
6021
6021
  var ZodFirstPartyTypeKind;
6022
6022
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6023
6023
  //#endregion
6024
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6024
+ //#region ../types/dist/sleep-DEZaLbiu.mjs
6025
6025
  /**
6026
6026
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6027
6027
  * window to float samples (D455).
@@ -6621,7 +6621,7 @@ var NOT_RUN = {
6621
6621
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6622
6622
  * because the hub (and this addon's boot) must not hang on a migration.
6623
6623
  */
6624
- async function runAddonMigrations(host, migrations, logger) {
6624
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6625
6625
  const first = migrations[0];
6626
6626
  if (first === void 0) return NOT_RUN;
6627
6627
  const owner = first.meta.owner;
@@ -6650,7 +6650,9 @@ async function runAddonMigrations(host, migrations, logger) {
6650
6650
  else if (status === "blocked") blocked.push(id);
6651
6651
  else skipped.push(id);
6652
6652
  };
6653
+ const selected = options.only === void 0 ? null : new Set(options.only);
6653
6654
  for (const step of declaration.steps) {
6655
+ if (selected !== null && !selected.has(step.id)) continue;
6654
6656
  const bound = byId.get(step.id);
6655
6657
  if (bound === void 0 || step.action === "skip") {
6656
6658
  skipped.push(step.id);
@@ -6828,6 +6830,12 @@ function projectStore(store, perNodeKeys, nodeId) {
6828
6830
  }
6829
6831
  return out;
6830
6832
  }
6833
+ /** Every scope, in the order the guard and the docs list them. */
6834
+ var SCOPED_SETTINGS_SCOPES = [
6835
+ "cluster",
6836
+ "device-defaults",
6837
+ "node"
6838
+ ];
6831
6839
  /**
6832
6840
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6833
6841
  *
@@ -7719,6 +7727,13 @@ var BaseAddon = class {
7719
7727
  */
7720
7728
  secretStatePaths = [];
7721
7729
  _addonSecretTree = null;
7730
+ /**
7731
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
7732
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
7733
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
7734
+ */
7735
+ _scopedByCap = /* @__PURE__ */ new Map();
7736
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7722
7737
  _deviceSecretTree = null;
7723
7738
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7724
7739
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7788,6 +7803,7 @@ var BaseAddon = class {
7788
7803
  this._ctx = context;
7789
7804
  this._secretSettings = null;
7790
7805
  }
7806
+ await this.loadScopedSchemas();
7791
7807
  await this.resolveConfig();
7792
7808
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7793
7809
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7797,6 +7813,7 @@ var BaseAddon = class {
7797
7813
  const normalized = normalizeAddonInitResult(result);
7798
7814
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7799
7815
  this._registeredCapNames = providers.map((p) => p.capability.name);
7816
+ await this.loadScopedSchemas();
7800
7817
  return normalized;
7801
7818
  }
7802
7819
  /**
@@ -7810,14 +7827,18 @@ var BaseAddon = class {
7810
7827
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7811
7828
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7812
7829
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7830
+ *
7831
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7832
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7833
+ * omitted applied ids "newer").
7813
7834
  */
7814
- async runMigrations(migrations) {
7835
+ async runMigrations(migrations, options) {
7815
7836
  const api = this.ctx.api.migrations;
7816
7837
  const report = await runAddonMigrations({
7817
7838
  declareOwner: (input) => api.declareOwner.mutate(input),
7818
7839
  startMigration: (input) => api.startMigration.mutate(input),
7819
7840
  finishMigration: (input) => api.finishMigration.mutate(input)
7820
- }, migrations, this.ctx.logger);
7841
+ }, migrations, this.ctx.logger, options);
7821
7842
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7822
7843
  return report;
7823
7844
  }
@@ -7881,6 +7902,16 @@ var BaseAddon = class {
7881
7902
  schema(schema) {
7882
7903
  return schema;
7883
7904
  }
7905
+ /**
7906
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
7907
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
7908
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
7909
+ * must already know which keys are per node. Names the providers register at init are added
7910
+ * once known.
7911
+ */
7912
+ scopedSettingsCapabilities() {
7913
+ return [];
7914
+ }
7884
7915
  /** Override to provide global-level settings UI schema. */
7885
7916
  globalSettingsSchema(_cap) {
7886
7917
  return null;
@@ -7924,7 +7955,8 @@ var BaseAddon = class {
7924
7955
  return [];
7925
7956
  }
7926
7957
  async getGlobalSettings(overlay, cap, nodeId) {
7927
- const schema = this.globalSettingsSchema(cap);
7958
+ await this.loadScopedSchemas(cap);
7959
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7928
7960
  if (!schema) return { sections: [] };
7929
7961
  const projected = await this.readRawProjectedStore(nodeId, cap);
7930
7962
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -7959,10 +7991,9 @@ var BaseAddon = class {
7959
7991
  *
7960
7992
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7961
7993
  * needs its connection fields, the default integration the addon's own sections. It is the
7962
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7963
- * unchanged (`integrations.setSettings` for an account integration).
7994
+ * SHAPE of the form only — the values live on the instance record.
7964
7995
  */
7965
- async integrationSettingsSchema(_instance) {
7996
+ async integrationFormSchema(_instance) {
7966
7997
  return null;
7967
7998
  }
7968
7999
  /**
@@ -8008,7 +8039,7 @@ var BaseAddon = class {
8008
8039
  * per-instance schema when it declares one, else its global schema (what they always showed).
8009
8040
  */
8010
8041
  async getIntegrationFormSchema(instance, nodeId) {
8011
- const scoped = await this.integrationSettingsSchema(instance);
8042
+ const scoped = await this.integrationFormSchema(instance);
8012
8043
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
8013
8044
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
8014
8045
  }
@@ -8056,6 +8087,7 @@ var BaseAddon = class {
8056
8087
  * resolved blob back is a no-op for every unchanged secret.
8057
8088
  */
8058
8089
  async resolveGlobalStore(nodeId, cap) {
8090
+ await this.loadScopedSchemas(cap);
8059
8091
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8060
8092
  return this.projectForNode(raw, nodeId, cap);
8061
8093
  }
@@ -8066,6 +8098,7 @@ var BaseAddon = class {
8066
8098
  }
8067
8099
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8068
8100
  async readRawProjectedStore(nodeId, cap) {
8101
+ await this.loadScopedSchemas(cap);
8069
8102
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8070
8103
  return this.projectForNode(raw, nodeId, cap);
8071
8104
  }
@@ -8168,6 +8201,7 @@ var BaseAddon = class {
8168
8201
  await this.applyGlobalPatch(patch, nodeId);
8169
8202
  }
8170
8203
  async applyGlobalPatch(barePatch, nodeId) {
8204
+ await this.loadScopedSchemas();
8171
8205
  const keys = this.perNodeKeys();
8172
8206
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8173
8207
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8181,7 +8215,8 @@ var BaseAddon = class {
8181
8215
  await this.resolveConfig();
8182
8216
  await this.onConfigChanged();
8183
8217
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8184
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8218
+ const legacy = this.globalSettingsSchema();
8219
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8185
8220
  }
8186
8221
  /**
8187
8222
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8189,14 +8224,67 @@ var BaseAddon = class {
8189
8224
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8190
8225
  * settings API behaves exactly like the legacy node-agnostic one.
8191
8226
  */
8192
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8227
+ /**
8228
+ * Load the scoped schemas of every capability this addon declares (the override and the
8229
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8230
+ * derived from the previous set. Idempotent.
8231
+ */
8232
+ async loadScopedSchemas(extraCap) {
8233
+ const caps = new Set([
8234
+ ...this.scopedSettingsCapabilities(),
8235
+ ...this._registeredCapNames,
8236
+ ...extraCap === void 0 ? [] : [extraCap]
8237
+ ]);
8238
+ let added = false;
8239
+ for (const cap of caps) {
8240
+ if (this._scopedByCap.has(cap)) continue;
8241
+ const loaded = [];
8242
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8243
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8244
+ if (schema !== null) loaded.push({
8245
+ scope,
8246
+ schema
8247
+ });
8248
+ }
8249
+ this._scopedByCap.set(cap, loaded);
8250
+ added = true;
8251
+ }
8252
+ if (!added) return;
8253
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8254
+ this._addonSecretTree = null;
8255
+ }
8256
+ /**
8257
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8258
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8259
+ */
8260
+ scopedFormSchema(cap) {
8261
+ const byId = /* @__PURE__ */ new Map();
8262
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8263
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
8264
+ }
8265
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
8266
+ loadedScopedSchemas(cap) {
8267
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
8268
+ return [...this._scopedByCap.values()].flat();
8269
+ }
8270
+ /**
8271
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
8272
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
8273
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
8274
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
8275
+ * Call {@link loadScopedSchemas} first (the async seams do).
8276
+ */
8193
8277
  perNodeKeys(cap) {
8194
8278
  const cacheKey = cap ?? "";
8195
- const cached = this._perNodeKeysCache.get(cacheKey);
8279
+ const cached = this._nodeKeysByCap.get(cacheKey);
8196
8280
  if (cached) return cached;
8197
- const schema = this.globalSettingsSchema(cap);
8198
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8199
- this._perNodeKeysCache.set(cacheKey, keys);
8281
+ const legacy = this.globalSettingsSchema(cap);
8282
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8283
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
8284
+ if (scope !== "node") continue;
8285
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
8286
+ }
8287
+ this._nodeKeysByCap.set(cacheKey, keys);
8200
8288
  return keys;
8201
8289
  }
8202
8290
  /**
@@ -8206,10 +8294,9 @@ var BaseAddon = class {
8206
8294
  * time to return its response before the addon is torn down and
8207
8295
  * re-initialised by `AddonRegistryService.restartAddon`.
8208
8296
  */
8209
- maybeAutoRestart(patchKeys, schema) {
8210
- if (!schema) return;
8297
+ maybeAutoRestart(patchKeys, schemas) {
8211
8298
  const restartKeys = /* @__PURE__ */ new Set();
8212
- for (const section of schema.sections) for (const field of section.fields) {
8299
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8213
8300
  if (field.type === "separator" || field.type === "info") continue;
8214
8301
  if (field.requiresRestart) restartKeys.add(field.key);
8215
8302
  }
@@ -8405,12 +8492,14 @@ var BaseAddon = class {
8405
8492
  * here, in the addon's own process, so the hub keeps no copy of it.
8406
8493
  */
8407
8494
  async getDeclaredSettingsKeys() {
8495
+ await this.loadScopedSchemas();
8408
8496
  return { keys: [...this.declaredKeySet()].toSorted() };
8409
8497
  }
8410
8498
  declaredKeySet() {
8411
8499
  const keys = new Set(Object.keys(this.defaults));
8412
8500
  const schema = this.globalSettingsSchema();
8413
8501
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8502
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8414
8503
  for (const key of this._declaredStateKeys) keys.add(key);
8415
8504
  for (const path of this.secretStatePaths) {
8416
8505
  const root = path.split(/[.[]/, 1)[0];
@@ -8506,7 +8595,11 @@ var BaseAddon = class {
8506
8595
  }
8507
8596
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8508
8597
  addonSecretTree() {
8509
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
8598
+ if (this._addonSecretTree === null) {
8599
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
8600
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
8601
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
8602
+ }
8510
8603
  return this._addonSecretTree;
8511
8604
  }
8512
8605
  deviceSecretTree() {
@@ -8756,6 +8849,23 @@ function dropPerNodeFields(fields) {
8756
8849
  }
8757
8850
  return kept;
8758
8851
  }
8852
+ /** The keys of the value-holding fields, recursing into layout containers. */
8853
+ function collectValueFieldKeys(fields) {
8854
+ const collected = [];
8855
+ for (const field of fields) {
8856
+ if (field.type === "group") {
8857
+ collected.push(...collectValueFieldKeys(field.fields));
8858
+ continue;
8859
+ }
8860
+ if (field.type === "sub-tabs") {
8861
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
8862
+ continue;
8863
+ }
8864
+ if (field.type === "separator" || field.type === "info") continue;
8865
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
8866
+ }
8867
+ return collected;
8868
+ }
8759
8869
  function collectFieldKeys(fields) {
8760
8870
  const collected = [];
8761
8871
  for (const field of fields) {
@@ -9275,6 +9385,7 @@ function defineEntryKind(name, spec) {
9275
9385
  class: "config",
9276
9386
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9277
9387
  retention: { none: "an entry goes only when the operator deletes it" },
9388
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9278
9389
  ...spec.database === void 0 ? {} : { database: spec.database },
9279
9390
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9280
9391
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -9971,6 +10082,28 @@ function toNodeId(idOrRunnerId) {
9971
10082
  const head = idOrRunnerId.split("/")[0];
9972
10083
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9973
10084
  }
10085
+ /**
10086
+ * Identity — preserves literal types for downstream inference.
10087
+ *
10088
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
10089
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
10090
+ * the broader unions declared on `CustomActionSpec`'s default generics.
10091
+ * Shape validity is enforced separately by the `customAction(...)` helper
10092
+ * whose return type is already a `CustomActionSpec<...>`.
10093
+ */
10094
+ function defineCustomActions(spec) {
10095
+ return spec;
10096
+ }
10097
+ function customAction(input, output, options) {
10098
+ return {
10099
+ input,
10100
+ output,
10101
+ kind: options?.kind ?? "query",
10102
+ auth: options?.auth ?? "protected",
10103
+ scope: options?.scope ?? { kind: "system" },
10104
+ ...options?.caller ? { caller: "required" } : {}
10105
+ };
10106
+ }
9974
10107
  Object.freeze({ "doorbell": "lastPressedAt" });
9975
10108
  /** Every capability name, so addon code can check a name without the schema graph. */
9976
10109
  var CAP_NAMES = Object.freeze([
@@ -11999,7 +12132,7 @@ object({
11999
12132
  params: record(string(), union([string(), number()])).optional()
12000
12133
  });
12001
12134
  //#endregion
12002
- //#region ../types/dist/composition-CRNwcFYY.mjs
12135
+ //#region ../types/dist/composition-pOHbTzRB.mjs
12003
12136
  var AUDIO_ENCODER_BY_CODEC = {
12004
12137
  opus: "libopus",
12005
12138
  aac: "aac",
@@ -15256,7 +15389,13 @@ var MigrationLedgerEntrySchema = object({
15256
15389
  * joined by the engine from the catalogues it knows this boot. Absent when no
15257
15390
  * catalogue lists the id (a newer database).
15258
15391
  */
15259
- meta: MigrationMetaSchema.optional()
15392
+ meta: MigrationMetaSchema.optional(),
15393
+ /**
15394
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15395
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15396
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15397
+ */
15398
+ ownerNotLoaded: boolean().optional()
15260
15399
  });
15261
15400
  /** A catalogued migration that is not applied, with where it stands. */
15262
15401
  var MigrationPendingEntrySchema = object({
@@ -50004,6 +50143,9 @@ var RunningProposalEvidenceSchema = object({
50004
50143
  runsFound: number().int().nonnegative(),
50005
50144
  pausesFound: number().int().nonnegative(),
50006
50145
  longestPauseMs: number().nonnegative(),
50146
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50147
+ pulsesFound: number().int().nonnegative(),
50148
+ longestPulseMs: number().nonnegative(),
50007
50149
  idleFloorW: number(),
50008
50150
  noiseCeilingW: number(),
50009
50151
  plateauW: number(),
@@ -51230,13 +51372,6 @@ var ExportInstanceUnknownError = class extends Error {
51230
51372
  function statusInstanceOf(input) {
51231
51373
  return "instanceId" in input ? input.instanceId : void 0;
51232
51374
  }
51233
- /**
51234
- * A single-instance provider's check: an absent id or its own passes, any other throws
51235
- * `ExportInstanceUnknownError`.
51236
- */
51237
- function assertOwnExportInstance(addon, own, instanceId) {
51238
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51239
- }
51240
51375
  var LinkStateSchema = _enum([
51241
51376
  "unlinked",
51242
51377
  "linked",
@@ -51341,12 +51476,12 @@ var deviceExportCapability = {
51341
51476
  kind: "poll"
51342
51477
  },
51343
51478
  /**
51344
- * Each export provider contributes its own per-device "Export" panel
51345
- * (enabled toggle, preferred stream, addon-specific knobs like the
51346
- * HA-MQTT discovery prefix). The three framework methods
51347
- * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /
51348
- * `applyDeviceSettingsPatch` are auto-injected on the provider
51349
- * interface and routed to the device-details aggregator.
51479
+ * Each export provider MAY contribute its own per-device "Export" panel
51480
+ * (enabled toggle, preferred stream, addon-specific knobs). The three
51481
+ * framework methods are mounted on the cap router when present.
51482
+ * `IDeviceExportProvider` leaves them optional: an exporter with no
51483
+ * per-device panel omits them (a `deviceConfig` cap's UI is derived and
51484
+ * never hand-written — D14 — and an exporter is not one of those).
51350
51485
  */
51351
51486
  exposesDeviceSettings: true,
51352
51487
  methods: {
@@ -55053,11 +55188,7 @@ var CreateIntegrationInputSchema = object({
55053
55188
  info: record(string(), unknown()).optional(),
55054
55189
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
55055
55190
  originStableId: string().optional(),
55056
- settings: record(string(), unknown()).optional(),
55057
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
55058
- * the keychain, not the table (D787). */
55059
- secretKeys: array(string()).optional(),
55060
- skipRestart: boolean().optional()
55191
+ settings: record(string(), unknown()).optional()
55061
55192
  });
55062
55193
  var UpdateIntegrationInputSchema = object({
55063
55194
  id: string(),
@@ -55078,16 +55209,6 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
55078
55209
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
55079
55210
  kind: "mutation",
55080
55211
  auth: "admin"
55081
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
55082
- id: string(),
55083
- settings: record(string(), unknown()),
55084
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
55085
- secretKeys: array(string()).optional(),
55086
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
55087
- skipRestart: boolean().optional()
55088
- }), object({ success: boolean() }), {
55089
- kind: "mutation",
55090
- auth: "admin"
55091
55212
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
55092
55213
  addonId: string(),
55093
55214
  settings: record(string(), unknown())
@@ -57812,6 +57933,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
57812
57933
  }), {
57813
57934
  kind: "mutation",
57814
57935
  auth: "admin"
57936
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
57937
+ rows: number().int().nonnegative(),
57938
+ secrets: number().int().nonnegative()
57939
+ }), {
57940
+ kind: "mutation",
57941
+ auth: "admin"
57942
+ }), method(object({
57943
+ integrationId: string().min(1),
57944
+ patch: record(string(), unknown())
57945
+ }), object({ written: boolean() }), {
57946
+ kind: "mutation",
57947
+ auth: "admin"
57948
+ }), method(object({
57949
+ integrationId: string().min(1),
57950
+ keys: array(string().min(1))
57951
+ }), object({
57952
+ present: boolean(),
57953
+ removed: record(string(), unknown())
57954
+ }), {
57955
+ kind: "mutation",
57956
+ auth: "admin"
57815
57957
  });
57816
57958
  method(object({
57817
57959
  sourceUrl: string(),
@@ -77187,11 +77329,15 @@ discriminatedUnion("kind", [object({
77187
77329
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77188
77330
  * near F. A device that is not near one level most of the time has no floor.
77189
77331
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77190
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77191
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77332
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77333
+ * display waking): it is neither a run nor a pause. Among the remaining
77334
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77335
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77336
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77337
+ * is no run.
77192
77338
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77193
- * grid a person would type; stop dwell covers the longest pause; start dwell
77194
- * covers the longest standby blip above T.
77339
+ * grid a person would type; stop dwell covers the longest pause and the
77340
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
77195
77341
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77196
77342
  * run must hold exactly one true interval and nothing may flap outside.
77197
77343
  */
@@ -77202,6 +77348,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
77202
77348
  30 * SECOND_MS;
77203
77349
  60 * SECOND_MS;
77204
77350
  20 * MINUTE_MS$1;
77351
+ 90 * SECOND_MS;
77352
+ 30 * MINUTE_MS$1;
77353
+ 10 * MINUTE_MS$1;
77354
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
77205
77355
  10 * SECOND_MS;
77206
77356
  10 * SECOND_MS;
77207
77357
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80957,13 +81107,6 @@ Object.freeze({
80957
81107
  access: "view",
80958
81108
  role: "admin"
80959
81109
  },
80960
- "integrations.getSettings": {
80961
- capName: "integrations",
80962
- capScope: "system",
80963
- addonId: null,
80964
- access: "view",
80965
- role: "admin"
80966
- },
80967
81110
  "integrations.list": {
80968
81111
  capName: "integrations",
80969
81112
  capScope: "system",
@@ -80971,13 +81114,6 @@ Object.freeze({
80971
81114
  access: "view",
80972
81115
  role: "admin"
80973
81116
  },
80974
- "integrations.setSettings": {
80975
- capName: "integrations",
80976
- capScope: "system",
80977
- addonId: null,
80978
- access: "create",
80979
- role: "admin"
80980
- },
80981
81117
  "integrations.testConnection": {
80982
81118
  capName: "integrations",
80983
81119
  capScope: "system",
@@ -81972,6 +82108,13 @@ Object.freeze({
81972
82108
  access: "view",
81973
82109
  role: "admin"
81974
82110
  },
82111
+ "migrations.clearLegacyIntegrationRows": {
82112
+ capName: "migrations",
82113
+ capScope: "system",
82114
+ addonId: null,
82115
+ access: "delete",
82116
+ role: "admin"
82117
+ },
81975
82118
  "migrations.declareOwner": {
81976
82119
  capName: "migrations",
81977
82120
  capScope: "system",
@@ -81979,6 +82122,13 @@ Object.freeze({
81979
82122
  access: "create",
81980
82123
  role: "admin"
81981
82124
  },
82125
+ "migrations.deleteLegacyIntegrationRowKeys": {
82126
+ capName: "migrations",
82127
+ capScope: "system",
82128
+ addonId: null,
82129
+ access: "delete",
82130
+ role: "admin"
82131
+ },
81982
82132
  "migrations.dryRun": {
81983
82133
  capName: "migrations",
81984
82134
  capScope: "system",
@@ -82014,6 +82164,20 @@ Object.freeze({
82014
82164
  access: "create",
82015
82165
  role: "admin"
82016
82166
  },
82167
+ "migrations.patchLegacyIntegrationRows": {
82168
+ capName: "migrations",
82169
+ capScope: "system",
82170
+ addonId: null,
82171
+ access: "create",
82172
+ role: "admin"
82173
+ },
82174
+ "migrations.readLegacyIntegrationRows": {
82175
+ capName: "migrations",
82176
+ capScope: "system",
82177
+ addonId: null,
82178
+ access: "view",
82179
+ role: "admin"
82180
+ },
82017
82181
  "migrations.restorePreMigration": {
82018
82182
  capName: "migrations",
82019
82183
  capScope: "system",
@@ -92240,6 +92404,17 @@ object({
92240
92404
  delay: number().nonnegative().optional(),
92241
92405
  commands: record(string(), unknown())
92242
92406
  });
92407
+ //#endregion
92408
+ //#region src/custom-actions.ts
92409
+ /**
92410
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92411
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92412
+ * because it unpairs every controller of the bridge.
92413
+ */
92414
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92415
+ kind: "mutation",
92416
+ auth: "admin"
92417
+ }) });
92243
92418
  process.platform, process.env["SystemRoot"];
92244
92419
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
92245
92420
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -139139,14 +139314,60 @@ function clearPairingFiles(accessoryUuid, logger) {
139139
139314
  } });
139140
139315
  }
139141
139316
  }
139317
+ //#endregion
139318
+ //#region src/hap-instance-kinds.ts
139319
+ /**
139320
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139321
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139322
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139323
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139324
+ * (`hapPersistDirOf`). The default instance is keyed by the
139325
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139326
+ * controller that paired before keeps working.
139327
+ */
139328
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139329
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139330
+ /**
139331
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139332
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139333
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139334
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139335
+ */
139336
+ function instanceSalt(instanceId) {
139337
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139338
+ }
139339
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139340
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139341
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139342
+ function hapPersistDirOf(instanceId) {
139343
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139344
+ }
139345
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139346
+ title: "HomeKit bridge",
139347
+ nameField: "name",
139348
+ schema: object({
139349
+ name: string().min(1),
139350
+ username: string().min(1),
139351
+ uuid: string().min(1),
139352
+ pincode: string().min(1).meta({ secret: true }),
139353
+ enabled: boolean().optional()
139354
+ })
139355
+ });
139356
+ function identityOfBody(body) {
139357
+ return {
139358
+ username: body.username,
139359
+ uuid: body.uuid,
139360
+ pincode: body.pincode
139361
+ };
139362
+ }
139142
139363
  /** Deterministic and distinct from every device accessory uuid. */
139143
- function actionSwitchUuid(actionId) {
139144
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139364
+ function actionSwitchUuid(actionId, instanceId) {
139365
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
139145
139366
  }
139146
139367
  function buildActionSwitch(input) {
139147
139368
  const { actionId, displayName, run } = input;
139148
139369
  const autoOffMs = input.autoOffMs ?? 1e3;
139149
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139370
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
139150
139371
  accessory.category = import_dist.Categories.SWITCH;
139151
139372
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
139152
139373
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -139220,6 +139441,10 @@ var ActionExports = class {
139220
139441
  exposedAs: e.displayName
139221
139442
  }));
139222
139443
  }
139444
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139445
+ accessoryUuids() {
139446
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139447
+ }
139223
139448
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
139224
139449
  async attachAll() {
139225
139450
  for (const entry of this.entries) try {
@@ -139287,6 +139512,7 @@ var ActionExports = class {
139287
139512
  const mapper = buildActionSwitch({
139288
139513
  actionId: entry.actionId,
139289
139514
  displayName: entry.displayName,
139515
+ instanceId: this.ports.instanceId,
139290
139516
  run: async () => {
139291
139517
  await runExportedAction(this.ports.api, this.ports.logger, {
139292
139518
  exporter: EXPORTER,
@@ -139427,6 +139653,128 @@ var BridgeHost = class {
139427
139653
  }
139428
139654
  };
139429
139655
  //#endregion
139656
+ //#region src/mappers/kind.ts
139657
+ /**
139658
+ * Which orchestrator a device gets, which device types the picker offers, and
139659
+ * what a device's HomeKit accessory is called on the wire.
139660
+ *
139661
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139662
+ * import the uuid convention without importing the registry that imports them.
139663
+ */
139664
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139665
+ /**
139666
+ * The device types the Export picker offers, and the answer to the cap's
139667
+ * `listSupportedDeviceKinds`.
139668
+ *
139669
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139670
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139671
+ * doctrine the HA exporter writes down, and the thing that confined the
139672
+ * previous exporter to cameras when it was ignored.
139673
+ *
139674
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139675
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139676
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139677
+ * absent — each needs a service whose semantics the table cannot yet honour,
139678
+ * and offering the tab before the mapping exists is how an operator gets an
139679
+ * accessory that pairs and does nothing.
139680
+ *
139681
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139682
+ * (`builders/generic/security-system.ts`), and the two things the table could
139683
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139684
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139685
+ * refuses the write out loud instead of pretending to arm.
139686
+ */
139687
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139688
+ DeviceType.Camera,
139689
+ DeviceType.Light,
139690
+ DeviceType.Switch,
139691
+ DeviceType.Siren,
139692
+ DeviceType.Sensor,
139693
+ DeviceType.Lock,
139694
+ DeviceType.Presence,
139695
+ DeviceType.AlarmPanel,
139696
+ DeviceType.Generic
139697
+ ];
139698
+ /**
139699
+ * Resolve the orchestrator for a device from its TYPE.
139700
+ *
139701
+ * `null` means "no Export tab": the picker must not offer a type no
139702
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139703
+ * to `camera` — that is what every entry persisted before this function existed
139704
+ * carries, and a transient API failure must never re-shape an exposed camera.
139705
+ */
139706
+ function pickMapperKind(deviceType) {
139707
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139708
+ if (deviceType === DeviceType.Camera) return "camera";
139709
+ const withheld = applianceExport("homekit", deviceType);
139710
+ if (withheld !== null && !withheld.exported) return null;
139711
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139712
+ }
139713
+ /**
139714
+ * The deterministic HAP accessory UUID for a device.
139715
+ *
139716
+ * One function, because three call sites depend on the answer agreeing: the
139717
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139718
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139719
+ * and the export sync state that records it.
139720
+ *
139721
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139722
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139723
+ * would make every paired camera a stranger. Generic devices get their own
139724
+ * namespace so a switch and a camera that happen to share a device id are not
139725
+ * the same HomeKit accessory.
139726
+ */
139727
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139728
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139729
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139730
+ }
139731
+ //#endregion
139732
+ //#region src/bridge-instance.ts
139733
+ var BridgeInstance = class {
139734
+ id;
139735
+ name;
139736
+ identity;
139737
+ bridgeHost;
139738
+ exposure;
139739
+ /** The devices of this bridge that have a live accessory, by device id. */
139740
+ exposed = /* @__PURE__ */ new Map();
139741
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139742
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139743
+ actionExports = null;
139744
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139745
+ syncState = /* @__PURE__ */ new Map();
139746
+ constructor(id, name, identity, bridgeHost, exposure) {
139747
+ this.id = id;
139748
+ this.name = name;
139749
+ this.identity = identity;
139750
+ this.bridgeHost = bridgeHost;
139751
+ this.exposure = exposure;
139752
+ }
139753
+ get pincode() {
139754
+ return this.identity.pincode;
139755
+ }
139756
+ findEntry(deviceId) {
139757
+ const id = String(deviceId);
139758
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139759
+ }
139760
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139761
+ accessoryUuidOf(kind, deviceId) {
139762
+ return accessoryUuidFor(kind, deviceId, this.id);
139763
+ }
139764
+ /**
139765
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139766
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139767
+ */
139768
+ pairingUuids() {
139769
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139770
+ return [
139771
+ this.identity.uuid,
139772
+ ...fromDevices,
139773
+ ...this.actionExports?.accessoryUuids() ?? []
139774
+ ];
139775
+ }
139776
+ };
139777
+ //#endregion
139430
139778
  //#region src/exposed-entry.ts
139431
139779
  /**
139432
139780
  * Carrying an exposed-device entry across a re-expose.
@@ -139513,81 +139861,31 @@ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139513
139861
  /** The settings keys that moved into the record; the migrations name them. */
139514
139862
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139515
139863
  //#endregion
139516
- //#region src/hap-instance-kinds.ts
139517
- /**
139518
- * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139519
- * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139520
- * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139521
- * the row). The directory its pairing state lives in is derived from the id, never stored
139522
- * (`hapPersistDirOf`). The default instance is keyed by the
139523
- * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139524
- * controller that paired before keeps working.
139525
- */
139526
- /** The default instance keeps its record under the addon id (it adopted the old identity). */
139527
- var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139528
- /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139529
- var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139530
- /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139531
- function hapPersistDirOf(instanceId) {
139532
- return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139533
- }
139534
- var hapBridgesKind = defineEntryKind("hap-bridges", {
139535
- title: "HomeKit bridge",
139536
- nameField: "name",
139537
- schema: object({
139538
- name: string().min(1),
139539
- username: string().min(1),
139540
- uuid: string().min(1),
139541
- pincode: string().min(1).meta({ secret: true }),
139542
- enabled: boolean().optional()
139543
- })
139544
- });
139545
- function identityOfBody(body) {
139546
- return {
139547
- username: body.username,
139548
- uuid: body.uuid,
139549
- pincode: body.pincode
139550
- };
139551
- }
139552
- //#endregion
139553
139864
  //#region src/hap-identity.ts
139554
139865
  /**
139555
- * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139556
- * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139557
- * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139558
- * A legacy identity without a record means the migration did not finish, and minting then would
139559
- * unpair every controller, so the addon refuses to boot with the reason.
139866
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139867
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139868
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139869
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139870
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139871
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139872
+ *
139873
+ * Every other instance is read as it is stored; this module is only about the default one.
139560
139874
  */
139561
- /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139562
- async function resolveBridgeIdentity(fixedPin, ports) {
139875
+ async function resolveDefaultBridge(ports) {
139563
139876
  const stored = await ports.readRecord();
139564
139877
  if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139565
- if (stored.kind === "resolved") {
139566
- if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139567
- await ports.patchPincode(fixedPin);
139568
- return {
139569
- identity: identityOfBody({
139570
- ...stored.body,
139571
- pincode: fixedPin
139572
- }),
139573
- minted: false
139574
- };
139575
- }
139576
- return {
139577
- identity: identityOfBody(stored.body),
139578
- minted: false
139579
- };
139580
- }
139581
- 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");
139582
- const fresh = ports.mint();
139583
- const body = fixedPin === null ? fresh : {
139584
- ...fresh,
139585
- pincode: fixedPin
139878
+ if (stored.kind === "resolved") return {
139879
+ kind: "existing",
139880
+ identity: identityOfBody(stored.body)
139586
139881
  };
139882
+ 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");
139883
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139884
+ const body = ports.mint();
139587
139885
  await ports.putFresh(body);
139588
139886
  return {
139589
- identity: identityOfBody(body),
139590
- minted: true
139887
+ kind: "minted",
139888
+ identity: identityOfBody(body)
139591
139889
  };
139592
139890
  }
139593
139891
  //#endregion
@@ -139814,12 +140112,87 @@ function legacyIdentityOf(value) {
139814
140112
  };
139815
140113
  }
139816
140114
  //#endregion
140115
+ //#region src/migrations/bridge-name-to-instance.ts
140116
+ async function moveBridgeNameToInstance(ports) {
140117
+ const name = (await ports.readBridgeName()).trim();
140118
+ if (name === "") return {
140119
+ outcome: "already-done",
140120
+ summary: { renamed: false }
140121
+ };
140122
+ const held = await ports.readDefaultRecord();
140123
+ if (held === null || held.name === name) return {
140124
+ outcome: "already-done",
140125
+ summary: { renamed: false }
140126
+ };
140127
+ await ports.patchDefaultName(name);
140128
+ const after = await ports.readDefaultRecord();
140129
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140130
+ return {
140131
+ outcome: "done",
140132
+ summary: { renamed: true }
140133
+ };
140134
+ }
140135
+ //#endregion
140136
+ //#region src/migrations/drop-global-knobs.ts
140137
+ /**
140138
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140139
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140140
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140141
+ * fact of one node, which the node row carries since the per-node migration.
140142
+ *
140143
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140144
+ * keychain value would be orphaned otherwise):
140145
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140146
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140147
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140148
+ * can never lose the value. A `@<nodeId>` row is never touched.
140149
+ */
140150
+ async function clearFixedPin(ports) {
140151
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140152
+ outcome: "already-done",
140153
+ summary: { cleared: false }
140154
+ };
140155
+ await ports.clearFixedPin();
140156
+ return {
140157
+ outcome: "done",
140158
+ summary: { cleared: true }
140159
+ };
140160
+ }
140161
+ async function planDropGlobalKnobRows(addonId, ports) {
140162
+ const stored = await ports.readStored([
140163
+ "bridgeName",
140164
+ "fixedPin",
140165
+ "interfaceName",
140166
+ nodeKeyOf("interfaceName")
140167
+ ]);
140168
+ const present = [
140169
+ "bridgeName",
140170
+ "fixedPin",
140171
+ "interfaceName"
140172
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140173
+ if (present.length === 0) return { edits: [] };
140174
+ const rowId = (key) => `${addonId}.${key}`;
140175
+ return { edits: [{
140176
+ op: "deleteKeys",
140177
+ scope: ADDON_SETTINGS_TABLE,
140178
+ keys: present.map(rowId),
140179
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140180
+ addonId,
140181
+ key,
140182
+ value: stored[key]
140183
+ }])))
140184
+ }] };
140185
+ }
140186
+ //#endregion
139817
140187
  //#region src/migrations/index.ts
139818
140188
  var EXPORT_HAP_ID = "export-hap";
139819
140189
  var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139820
140190
  var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139821
140191
  var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139822
140192
  var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140193
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140194
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140195
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
139823
140196
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
139824
140197
  var ADDON_MIGRATIONS = [
139825
140198
  {
@@ -139888,7 +140261,7 @@ var ADDON_MIGRATIONS = [
139888
140261
  },
139889
140262
  {
139890
140263
  meta: {
139891
- id: "export-hap/2026-11-04-drop-exposure-keys",
140264
+ id: DROP_EXPOSURE_KEYS_ID,
139892
140265
  owner: EXPORT_HAP_ID,
139893
140266
  level: "addon-state",
139894
140267
  seq: 5,
@@ -139901,6 +140274,58 @@ var ADDON_MIGRATIONS = [
139901
140274
  fixtureMark: "the bridge name the migration does not know"
139902
140275
  },
139903
140276
  plan: planDropExposureKeys
140277
+ },
140278
+ {
140279
+ meta: {
140280
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140281
+ owner: EXPORT_HAP_ID,
140282
+ level: "addon-state",
140283
+ seq: 6,
140284
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140285
+ store: "settings",
140286
+ scope: "cluster",
140287
+ onFailure: "block-owner",
140288
+ bodyKind: "procedure",
140289
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140290
+ fixtureMark: "the bridge name the migration does not know"
140291
+ },
140292
+ procedure: moveBridgeNameToInstance
140293
+ },
140294
+ {
140295
+ meta: {
140296
+ id: DROP_GLOBAL_KNOBS_ID,
140297
+ owner: EXPORT_HAP_ID,
140298
+ level: "addon-state",
140299
+ seq: 7,
140300
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140301
+ store: "settings",
140302
+ scope: "cluster",
140303
+ onFailure: "tolerate",
140304
+ bodyKind: "procedure",
140305
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140306
+ fixtureMark: "the bridge name the migration does not know"
140307
+ },
140308
+ procedure: clearFixedPin
140309
+ },
140310
+ {
140311
+ meta: {
140312
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140313
+ owner: EXPORT_HAP_ID,
140314
+ level: "addon-state",
140315
+ seq: 8,
140316
+ dependsOn: [
140317
+ BRIDGE_NAME_TO_INSTANCE_ID,
140318
+ DROP_GLOBAL_KNOBS_ID,
140319
+ INTERFACE_NAME_PER_NODE_ID
140320
+ ],
140321
+ store: "settings",
140322
+ scope: "cluster",
140323
+ onFailure: "tolerate",
140324
+ bodyKind: "plan",
140325
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140326
+ fixtureMark: "the bridge name the migration does not know"
140327
+ },
140328
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
139904
140329
  }
139905
140330
  ];
139906
140331
  //#endregion
@@ -157995,81 +158420,6 @@ function errMsg$3(err) {
157995
158420
  return err instanceof Error ? err.message : String(err);
157996
158421
  }
157997
158422
  //#endregion
157998
- //#region src/mappers/kind.ts
157999
- /**
158000
- * Which orchestrator a device gets, which device types the picker offers, and
158001
- * what a device's HomeKit accessory is called on the wire.
158002
- *
158003
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
158004
- * import the uuid convention without importing the registry that imports them.
158005
- */
158006
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
158007
- /**
158008
- * The device types the Export picker offers, and the answer to the cap's
158009
- * `listSupportedDeviceKinds`.
158010
- *
158011
- * A UI FILTER, nothing more. Whether a device actually exports anything is
158012
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
158013
- * doctrine the HA exporter writes down, and the thing that confined the
158014
- * previous exporter to cameras when it was ignored.
158015
- *
158016
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
158017
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
158018
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
158019
- * absent — each needs a service whose semantics the table cannot yet honour,
158020
- * and offering the tab before the mapping exists is how an operator gets an
158021
- * accessory that pairs and does nothing.
158022
- *
158023
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
158024
- * (`builders/generic/security-system.ts`), and the two things the table could
158025
- * not previously honour are now honoured explicitly: HomeKit is only ever
158026
- * offered the arm modes the panel accepts, and a panel that requires a PIN
158027
- * refuses the write out loud instead of pretending to arm.
158028
- */
158029
- var HAP_EXPORTABLE_DEVICE_TYPES = [
158030
- DeviceType.Camera,
158031
- DeviceType.Light,
158032
- DeviceType.Switch,
158033
- DeviceType.Siren,
158034
- DeviceType.Sensor,
158035
- DeviceType.Lock,
158036
- DeviceType.Presence,
158037
- DeviceType.AlarmPanel,
158038
- DeviceType.Generic
158039
- ];
158040
- /**
158041
- * Resolve the orchestrator for a device from its TYPE.
158042
- *
158043
- * `null` means "no Export tab": the picker must not offer a type no
158044
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
158045
- * to `camera` — that is what every entry persisted before this function existed
158046
- * carries, and a transient API failure must never re-shape an exposed camera.
158047
- */
158048
- function pickMapperKind(deviceType) {
158049
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
158050
- if (deviceType === DeviceType.Camera) return "camera";
158051
- const withheld = applianceExport("homekit", deviceType);
158052
- if (withheld !== null && !withheld.exported) return null;
158053
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
158054
- }
158055
- /**
158056
- * The deterministic HAP accessory UUID for a device.
158057
- *
158058
- * One function, because three call sites depend on the answer agreeing: the
158059
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
158060
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
158061
- * and the export sync state that records it.
158062
- *
158063
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
158064
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
158065
- * would make every paired camera a stranger. Generic devices get their own
158066
- * namespace so a switch and a camera that happen to share a device id are not
158067
- * the same HomeKit accessory.
158068
- */
158069
- function accessoryUuidFor(kind, deviceId) {
158070
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
158071
- }
158072
- //#endregion
158073
158423
  //#region src/multi-tier/rtp-streaming-control.ts
158074
158424
  /**
158075
158425
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -158872,7 +159222,7 @@ async function buildCameraAccessory(input) {
158872
159222
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
158873
159223
  const isDoorbell = capNames.has("doorbell");
158874
159224
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
158875
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159225
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
158876
159226
  accessory.category = category;
158877
159227
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
158878
159228
  const bctx = {
@@ -159007,7 +159357,7 @@ async function buildGenericAccessory(input) {
159007
159357
  const rows = rowsForCaps(capNames);
159008
159358
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
159009
159359
  const deviceType = await resolveDeviceType(proxy);
159010
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159360
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
159011
159361
  accessory.category = accessoryCategoryFor(deviceType);
159012
159362
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
159013
159363
  const bctx = {
@@ -159240,8 +159590,6 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159240
159590
  }
159241
159591
  ];
159242
159592
  var DEFAULT_CONFIG = {
159243
- bridgeName: "CamStack Bridge",
159244
- fixedPin: "",
159245
159593
  interfaceName: "",
159246
159594
  clipRetentionDays: 14,
159247
159595
  exportSyncState: {}
@@ -159260,10 +159608,6 @@ var BANNED_PINCODES = new Set([
159260
159608
  "123-45-678",
159261
159609
  "876-54-321"
159262
159610
  ]);
159263
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
159264
- function isValidPincode(pin) {
159265
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
159266
- }
159267
159611
  function generateUsername() {
159268
159612
  const bytes = randomBytes(6);
159269
159613
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -159278,33 +159622,23 @@ function generatePincode() {
159278
159622
  }
159279
159623
  throw new Error("export-hap: failed to generate a non-trivial pincode");
159280
159624
  }
159625
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
159281
159626
  function buildBridgeUuid(bridgeName) {
159282
159627
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
159283
159628
  }
159284
159629
  var ExportHapAddon = class extends BaseAddon {
159285
159630
  /**
159286
- * The old `identity.pincode` secret: declared only so the identity migration can release its
159287
- * keychain entry when it clears the old setting. The identity itself is a record now.
159631
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159632
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159288
159633
  */
159289
- secretStatePaths = ["identity.pincode"];
159290
- exposed = /* @__PURE__ */ new Map();
159291
- /** The exported actions — switches beside the devices (D968). */
159292
- actionExports = null;
159634
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159635
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159636
+ bridges = /* @__PURE__ */ new Map();
159637
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159638
+ lifecycle = Promise.resolve();
159293
159639
  lastError;
159294
159640
  /** The HomeKit instances (D985): one record per bridge identity. */
159295
159641
  instances = null;
159296
- /**
159297
- * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159298
- * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159299
- * boot and written through on every change; this addon is the record's only writer.
159300
- */
159301
- exposure = {
159302
- name: HAP_EXPOSURE_NAME,
159303
- devices: [],
159304
- actions: []
159305
- };
159306
- /** Shared HAP setup code applied to every published accessory. */
159307
- pincode = "";
159308
159642
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
159309
159643
  bind;
159310
159644
  /**
@@ -159348,12 +159682,6 @@ var ExportHapAddon = class extends BaseAddon {
159348
159682
  hksvBuilds = new HksvBuildOutcomes();
159349
159683
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
159350
159684
  hksvClipPlanes = null;
159351
- /**
159352
- * THE bridge. Lazily created and published the first time a non-camera
159353
- * accessory needs it; never torn down while the addon runs, because an
159354
- * unpublish would drop a pairing the operator already entered a code for.
159355
- */
159356
- bridgeHost = null;
159357
159685
  constructor() {
159358
159686
  super({ ...DEFAULT_CONFIG });
159359
159687
  }
@@ -159367,31 +159695,24 @@ var ExportHapAddon = class extends BaseAddon {
159367
159695
  this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159368
159696
  description: {
159369
159697
  role: "services",
159370
- instanceMode: "single",
159698
+ instanceMode: "multiple",
159371
159699
  kind: "bridge",
159372
159700
  canTest: false
159373
159701
  },
159374
- formSchema: () => this.schema({ sections: [] }),
159702
+ formSchema: (id) => this.bridgeForm(id),
159375
159703
  initialBody: (name) => ({
159376
159704
  name,
159377
159705
  username: generateUsername(),
159378
159706
  uuid: buildBridgeUuid(name),
159379
159707
  pincode: generatePincode()
159380
159708
  }),
159381
- configured: (body) => body.username !== "" && body.pincode !== ""
159709
+ mintId: () => `hap-${randomUUID().slice(0, 8)}`,
159710
+ configured: (body) => body.username !== "" && body.pincode !== "",
159711
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159382
159712
  });
159383
159713
  await this.migrateSettings();
159384
- const identity = await this.ensureIdentity();
159385
- await this.loadExposure();
159386
- this.pincode = identity.pincode;
159714
+ await this.ensureDefaultBridge();
159387
159715
  this.bind = this.config.interfaceName || void 0;
159388
- this.bridgeHost = new BridgeHost({
159389
- displayName: this.config.bridgeName,
159390
- uuid: identity.uuid,
159391
- pincode: identity.pincode,
159392
- bind: this.bind,
159393
- logger: this.ctx.logger
159394
- });
159395
159716
  try {
159396
159717
  await initHapStorage(path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
159397
159718
  } catch (err) {
@@ -159405,7 +159726,7 @@ var ExportHapAddon = class extends BaseAddon {
159405
159726
  this.hksvClipStore = new HksvClipStore({
159406
159727
  logger: this.ctx.logger.child("hksv-clips"),
159407
159728
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
159408
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159729
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159409
159730
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
159410
159731
  resolveFfmpeg: this.pinnedFfmpeg,
159411
159732
  spawnFn: spawn,
@@ -159418,161 +159739,323 @@ var ExportHapAddon = class extends BaseAddon {
159418
159739
  }) })
159419
159740
  });
159420
159741
  await this.serveHksvClipPlanes();
159742
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159743
+ for (const row of ordered) try {
159744
+ await this.startInstance(row.id);
159745
+ } catch (err) {
159746
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159747
+ instanceId: row.id,
159748
+ error: errMsg(err)
159749
+ } });
159750
+ }
159751
+ this.ctx.addDisposer(async () => {
159752
+ await this.enqueue(async () => {
159753
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159754
+ });
159755
+ });
159756
+ this.subscribeDeviceProvisionedForReconcile();
159757
+ this.subscribeDeviceReadyForReconcile();
159758
+ this.subscribeStorageLocationsForClips();
159759
+ const provider = this.buildExportProvider();
159760
+ const clipsProvider = createHksvVideoclipsProvider({
159761
+ logger: this.ctx.logger.child("hksv-clips"),
159762
+ addonId: EXPORT_HAP_ADDON_ID,
159763
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159764
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159765
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159766
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159767
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159768
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159769
+ });
159770
+ return {
159771
+ providers: [
159772
+ {
159773
+ capability: deviceExportCapability,
159774
+ provider
159775
+ },
159776
+ {
159777
+ capability: videoclipsCapability,
159778
+ provider: clipsProvider
159779
+ },
159780
+ {
159781
+ capability: integrationInstancesCapability,
159782
+ provider: this.requireInstances().toProvider()
159783
+ }
159784
+ ],
159785
+ customActions: exportHapActions,
159786
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159787
+ };
159788
+ }
159789
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159790
+ enqueue(job) {
159791
+ const run = this.lifecycle.then(job);
159792
+ this.lifecycle = run.then(() => void 0, () => void 0);
159793
+ return run;
159794
+ }
159795
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159796
+ instanceForDevice(deviceId) {
159797
+ const key = String(deviceId);
159798
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159799
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159800
+ }
159801
+ requireBridge(instanceId) {
159802
+ const inst = this.bridges.get(instanceId);
159803
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159804
+ return inst;
159805
+ }
159806
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159807
+ async startInstance(id) {
159808
+ await this.stopInstance(id);
159809
+ const resolved = await this.requireInstances().readResolved(id);
159810
+ if (resolved === null || !resolved.enabled) return;
159811
+ if (resolved.secrets === "unavailable") {
159812
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159813
+ return;
159814
+ }
159815
+ const identity = identityOfBody(resolved.body);
159816
+ const exposure = await this.loadExposure(id);
159817
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159818
+ displayName: resolved.body.name,
159819
+ uuid: identity.uuid,
159820
+ pincode: identity.pincode,
159821
+ bind: this.bind,
159822
+ logger: this.ctx.logger
159823
+ }), exposure);
159824
+ this.bridges.set(id, inst);
159825
+ this.warnOnDuplicateName(inst);
159421
159826
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
159422
- const cleaned = this.exposure.devices.filter((entry) => {
159827
+ const cleaned = inst.exposure.devices.filter((entry) => {
159423
159828
  if (validKinds.has(entry.mapperKind)) return true;
159424
159829
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
159425
159830
  return false;
159426
159831
  });
159427
- if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
159832
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
159428
159833
  for (const entry of cleaned) {
159429
159834
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
159430
159835
  try {
159431
- await this.attachMapper(entry);
159836
+ await this.attachMapper(inst, entry);
159432
159837
  const numericId = Number.parseInt(entry.deviceId, 10);
159433
159838
  if (Number.isFinite(numericId)) {
159434
- const fp = await this.computeExportFingerprint(numericId);
159435
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159839
+ const fp = await this.computeExportFingerprint(inst, numericId);
159840
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159436
159841
  }
159437
159842
  } catch (err) {
159438
159843
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
159439
159844
  }
159440
159845
  }
159441
- this.actionExports = new ActionExports({
159846
+ inst.actionExports = new ActionExports({
159442
159847
  api: this.ctx.api,
159443
159848
  logger: this.ctx.logger,
159849
+ instanceId: id,
159444
159850
  publish: async (accessory) => {
159445
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159851
+ if (await inst.bridgeHost.add(accessory)) return;
159446
159852
  await publishStandalone(accessory, {
159447
- pincode: this.pincode,
159853
+ pincode: inst.pincode,
159448
159854
  port: 0,
159449
159855
  bind: this.bind,
159450
159856
  logger: this.ctx.logger
159451
159857
  });
159452
159858
  },
159453
159859
  unpublish: async (accessory) => {
159454
- if (this.bridgeHost?.holds(accessory) === true) {
159455
- this.bridgeHost.remove(accessory);
159860
+ if (inst.bridgeHost.holds(accessory)) {
159861
+ inst.bridgeHost.remove(accessory);
159456
159862
  return;
159457
159863
  }
159458
159864
  await unpublishAccessory(accessory, this.ctx.logger);
159459
159865
  },
159460
- persist: (entries) => this.setExposedActions(entries)
159461
- }, this.exposure.actions);
159462
- await this.actionExports.attachAll();
159463
- await this.actionExports.reconcile();
159464
- this.ctx.addDisposer(async () => {
159465
- await this.actionExports?.dispose();
159466
- await this.detachAll();
159467
- await this.bridgeHost?.dispose();
159866
+ persist: (entries) => this.setExposedActions(inst, entries)
159867
+ }, inst.exposure.actions);
159868
+ await inst.actionExports.attachAll();
159869
+ await inst.actionExports.reconcile();
159870
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159871
+ instanceId: id,
159872
+ name: inst.name,
159873
+ devices: inst.exposed.size
159874
+ } });
159875
+ }
159876
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159877
+ async stopInstance(id) {
159878
+ const inst = this.bridges.get(id);
159879
+ if (inst === void 0) return;
159880
+ this.bridges.delete(id);
159881
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159882
+ inst.pendingRebuildTimers.clear();
159883
+ await inst.actionExports?.dispose();
159884
+ await this.detachAll(inst);
159885
+ await inst.bridgeHost.dispose();
159886
+ }
159887
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159888
+ async applyChange(id, change) {
159889
+ if (change === "deleted") {
159890
+ await this.removeInstance(id);
159891
+ return;
159892
+ }
159893
+ const resolved = await this.requireInstances().readResolved(id);
159894
+ if (resolved === null || !resolved.enabled) {
159895
+ await this.stopInstance(id);
159896
+ return;
159897
+ }
159898
+ const running = this.bridges.get(id);
159899
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159900
+ const next = identityOfBody(resolved.body);
159901
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159902
+ }
159903
+ await this.startInstance(id);
159904
+ }
159905
+ /**
159906
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159907
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159908
+ */
159909
+ async removeInstance(id) {
159910
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159911
+ await this.stopInstance(id);
159912
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159913
+ await this.exposureHandle().delete(id);
159914
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159915
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159916
+ }
159917
+ /**
159918
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159919
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159920
+ * devices stay.
159921
+ */
159922
+ regenerateBridge(instanceId) {
159923
+ return this.enqueue(async () => {
159924
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159925
+ await this.stopInstance(instanceId);
159926
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159927
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159928
+ await this.startInstance(instanceId);
159929
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159930
+ instanceId,
159931
+ accessories: uuids.length
159932
+ } });
159933
+ return { regenerated: true };
159468
159934
  });
159469
- this.subscribeDeviceProvisionedForReconcile();
159470
- this.subscribeDeviceReadyForReconcile();
159471
- this.subscribeStorageLocationsForClips();
159472
- this.disposeSharedRebuildTimers();
159473
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
159474
- const provider = {
159475
- getStatus: async (input) => {
159476
- ownInstance(statusInstanceOf(input));
159477
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
159478
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159479
- const setup = this.buildSetupBlock();
159480
- return {
159481
- linkState,
159482
- exposedDeviceCount: this.exposed.size,
159483
- ...this.lastError ? { error: this.lastError } : {},
159484
- ...setup ? { setup } : {}
159485
- };
159486
- },
159487
- listInstances: async () => [{
159488
- instanceId: EXPORT_HAP_ADDON_ID,
159489
- name: "HomeKit",
159490
- enabled: true,
159935
+ }
159936
+ warnOnDuplicateName(inst) {
159937
+ const key = inst.name.trim().toLowerCase();
159938
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159939
+ if (others.length === 0) return;
159940
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159941
+ instanceId: inst.id,
159942
+ name: inst.name,
159943
+ others: others.map((b) => b.id)
159944
+ } });
159945
+ }
159946
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159947
+ bridgeForm(id) {
159948
+ const inst = id === null ? void 0 : this.bridges.get(id);
159949
+ let qr = "";
159950
+ try {
159951
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159952
+ } catch (err) {
159953
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159954
+ instanceId: id,
159955
+ error: errMsg(err)
159956
+ } });
159957
+ }
159958
+ return this.schema({ sections: [{
159959
+ id: "bridge",
159960
+ title: "HomeKit bridge",
159961
+ 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.",
159962
+ fields: [...inst === void 0 ? [] : [{
159963
+ type: "info",
159964
+ key: "setupCode",
159965
+ label: "Setup code",
159966
+ content: inst.pincode
159967
+ }, ...qr === "" ? [] : [{
159968
+ type: "qr-code",
159969
+ key: "setupQr",
159970
+ label: "Pairing QR",
159971
+ caption: "Scan with the iOS Camera app.",
159972
+ value: qr,
159973
+ size: 192
159974
+ }]], ...id === null ? [] : [{
159975
+ type: "addon-action-button",
159976
+ key: "__regenerate-bridge",
159977
+ label: "Regenerate setup code",
159978
+ 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.",
159979
+ addonId: EXPORT_HAP_ADDON_ID,
159980
+ action: "regenerateBridge",
159981
+ buttonLabel: "Regenerate",
159982
+ variant: "danger",
159983
+ paramsStatic: { instanceId: id },
159984
+ 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."
159985
+ }]]
159986
+ }] });
159987
+ }
159988
+ /** Whole-addon status of the bridges: linked when any is paired. */
159989
+ statusOf(bridges) {
159990
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
159991
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159992
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
159993
+ return {
159994
+ linkState,
159995
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
159996
+ ...this.lastError ? { error: this.lastError } : {},
159997
+ ...setup ? { setup } : {}
159998
+ };
159999
+ }
160000
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
160001
+ bridgesOf(instanceId) {
160002
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
160003
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
160004
+ }
160005
+ buildExportProvider() {
160006
+ return {
160007
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
160008
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
160009
+ instanceId: row.id,
160010
+ name: row.body.name,
160011
+ enabled: row.enabled,
159491
160012
  kind: "hap-bridge"
159492
- }],
160013
+ })),
159493
160014
  listSupportedDeviceKinds: async ({ instanceId }) => {
159494
- ownInstance(instanceId);
160015
+ this.bridgesOf(instanceId);
159495
160016
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
159496
160017
  },
159497
- listExposedDevices: async ({ instanceId }) => {
159498
- ownInstance(instanceId);
159499
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159500
- const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159501
- return {
159502
- deviceId,
159503
- exposedAs: m.accessory.displayName,
159504
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159505
- };
159506
- });
159507
- },
159508
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159509
- ownInstance(instanceId);
159510
- return this.exposeDevice(deviceId, capabilities);
159511
- },
159512
- unexposeDevice: async ({ instanceId, deviceId }) => {
159513
- ownInstance(instanceId);
159514
- return this.unexposeDevice(deviceId);
159515
- },
160018
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
160019
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
160020
+ return {
160021
+ deviceId,
160022
+ exposedAs: m.accessory.displayName,
160023
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
160024
+ };
160025
+ })),
160026
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
160027
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
159516
160028
  listSupportedEntityKinds: async () => ["device", "action"],
159517
160029
  listExposedEntities: async ({ instanceId }) => {
159518
- ownInstance(instanceId);
159519
- await this.actionExports?.reconcile();
159520
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
159521
- entity: {
159522
- kind: "device",
159523
- deviceId
159524
- },
159525
- exposedAs: m.accessory.displayName
159526
- })), ...this.actionExports?.list() ?? []];
160030
+ const out = [];
160031
+ for (const inst of this.bridgesOf(instanceId)) {
160032
+ await inst.actionExports?.reconcile();
160033
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
160034
+ entity: {
160035
+ kind: "device",
160036
+ deviceId
160037
+ },
160038
+ exposedAs: m.accessory.displayName
160039
+ })), ...inst.actionExports?.list() ?? []);
160040
+ }
160041
+ return out;
159527
160042
  },
159528
160043
  exposeEntity: async ({ instanceId, entity }) => {
159529
- ownInstance(instanceId);
159530
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
159531
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
160044
+ const inst = this.requireBridge(instanceId);
160045
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
160046
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
159532
160047
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159533
160048
  },
159534
160049
  unexposeEntity: async ({ instanceId, entity }) => {
159535
- ownInstance(instanceId);
159536
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
159537
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
160050
+ const inst = this.requireBridge(instanceId);
160051
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
160052
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
159538
160053
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159539
160054
  },
159540
160055
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
159541
160056
  getDeviceLiveContribution: async () => null,
159542
160057
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
159543
160058
  };
159544
- const clipsProvider = createHksvVideoclipsProvider({
159545
- logger: this.ctx.logger.child("hksv-clips"),
159546
- addonId: EXPORT_HAP_ADDON_ID,
159547
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
159548
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159549
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159550
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159551
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159552
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159553
- });
159554
- return [
159555
- {
159556
- capability: deviceExportCapability,
159557
- provider
159558
- },
159559
- {
159560
- capability: videoclipsCapability,
159561
- provider: clipsProvider
159562
- },
159563
- {
159564
- capability: integrationInstancesCapability,
159565
- provider: this.requireInstances().toProvider()
159566
- }
159567
- ];
159568
- }
159569
- async onConfigChanged() {
159570
- const fixedPin = this.config.fixedPin;
159571
- if (!fixedPin || !isValidPincode(fixedPin)) return;
159572
- const handle = this.requireRecords().kind(hapBridgesKind);
159573
- const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159574
- if (row === null || row.data.pincode === fixedPin) return;
159575
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159576
160059
  }
159577
160060
  requireInstances() {
159578
160061
  if (this.instances === null) throw new Error("export-hap: instances are not initialised");
@@ -159606,13 +160089,17 @@ var ExportHapAddon = class extends BaseAddon {
159606
160089
  }
159607
160090
  return "created";
159608
160091
  },
159609
- readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
160092
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
160093
+ patchDefaultName: async (name) => {
160094
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
160095
+ },
160096
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
159610
160097
  };
159611
160098
  }
159612
- /** The identity of the default instance; see `resolveBridgeIdentity`. */
159613
- async ensureIdentity() {
160099
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
160100
+ async ensureDefaultBridge() {
159614
160101
  const handle = this.requireRecords().kind(hapBridgesKind);
159615
- const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
160102
+ const boot = await resolveDefaultBridge({
159616
160103
  readRecord: async () => {
159617
160104
  const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159618
160105
  if (resolved === null) return { kind: "absent" };
@@ -159622,9 +160109,7 @@ var ExportHapAddon = class extends BaseAddon {
159622
160109
  } : { kind: "unavailable" };
159623
160110
  },
159624
160111
  legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159625
- patchPincode: async (pincode) => {
159626
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159627
- },
160112
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
159628
160113
  putFresh: async (body) => {
159629
160114
  await handle.put({
159630
160115
  id: HAP_DEFAULT_INSTANCE_ID,
@@ -159632,14 +160117,13 @@ var ExportHapAddon = class extends BaseAddon {
159632
160117
  }, { ifRev: 0 });
159633
160118
  },
159634
160119
  mint: () => ({
159635
- name: this.config.bridgeName,
160120
+ name: DEFAULT_BRIDGE_NAME,
159636
160121
  username: generateUsername(),
159637
- uuid: buildBridgeUuid(this.config.bridgeName),
160122
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
159638
160123
  pincode: generatePincode()
159639
160124
  })
159640
160125
  });
159641
- if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159642
- return identity;
160126
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
159643
160127
  }
159644
160128
  /**
159645
160129
  * Build the generic `device-export` `setup` block surfaced via
@@ -159648,10 +160132,10 @@ var ExportHapAddon = class extends BaseAddon {
159648
160132
  * a copyable field, and a short pairing instruction. Returns `null`
159649
160133
  * until the bridge has booted and produced both values.
159650
160134
  */
159651
- buildSetupBlock() {
159652
- const setupCode = this.pincode;
160135
+ buildSetupBlock(inst) {
160136
+ const setupCode = inst.pincode;
159653
160137
  if (!setupCode) return null;
159654
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160138
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
159655
160139
  return {
159656
160140
  ...qr !== void 0 ? { qr } : {},
159657
160141
  fields: [{
@@ -159672,18 +160156,18 @@ var ExportHapAddon = class extends BaseAddon {
159672
160156
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
159673
160157
  * still said `streamPreference=auto`.
159674
160158
  */
159675
- async exposeDevice(deviceId, capabilities, settings) {
160159
+ async exposeDevice(inst, deviceId, capabilities, settings) {
159676
160160
  const numericId = Number.parseInt(deviceId, 10);
159677
160161
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159678
- if (this.exposed.has(deviceId)) {
160162
+ if (inst.exposed.has(deviceId)) {
159679
160163
  log.debug("export-hap: device already exposed — refreshing capabilities");
159680
- await this.detachMapper(deviceId);
160164
+ await this.detachMapper(inst, deviceId);
159681
160165
  }
159682
160166
  const summary = await this.fetchDeviceSummary(numericId);
159683
160167
  const mapperKind = pickMapperKind(summary?.type);
159684
160168
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
159685
160169
  const displayName = summary?.name ?? `Device ${deviceId}`;
159686
- const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
160170
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159687
160171
  const rebuilt = {
159688
160172
  deviceId,
159689
160173
  displayName,
@@ -159695,37 +160179,38 @@ var ExportHapAddon = class extends BaseAddon {
159695
160179
  ...rebuilt,
159696
160180
  settings
159697
160181
  }, previous, ["settings", "capabilities"]);
159698
- const attached = await this.attachMapper(baseEntry);
160182
+ const attached = await this.attachMapper(inst, baseEntry);
159699
160183
  const finalEntry = {
159700
160184
  ...baseEntry,
159701
160185
  childAccessoryUuids: attached.childAccessoryUuids
159702
160186
  };
159703
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
160187
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
159704
160188
  next.push(finalEntry);
159705
- await this.setExposedDevices(next);
160189
+ await this.setExposedDevices(inst, next);
159706
160190
  if (Number.isFinite(numericId)) {
159707
- const fp = await this.computeExportFingerprint(numericId);
159708
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160191
+ const fp = await this.computeExportFingerprint(inst, numericId);
160192
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159709
160193
  }
159710
160194
  log.info("export-hap: exposed device", { meta: {
160195
+ instanceId: inst.id,
159711
160196
  displayName,
159712
160197
  mapperKind,
159713
160198
  childCount: attached.childAccessoryUuids.length
159714
160199
  } });
159715
160200
  }
159716
- async unexposeDevice(deviceId, options = {}) {
160201
+ async unexposeDevice(inst, deviceId, options = {}) {
159717
160202
  const numericId = Number.parseInt(deviceId, 10);
159718
160203
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159719
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
159720
- await this.detachMapper(deviceId);
159721
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159722
- if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
159723
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
159724
- await this.forgetFingerprint(numericId);
160204
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160205
+ await this.detachMapper(inst, deviceId);
160206
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160207
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160208
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160209
+ await this.forgetFingerprint(inst, numericId);
159725
160210
  this.hksvBuilds.forget(numericId);
159726
- log.info("export-hap: unexposed device");
160211
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
159727
160212
  }
159728
- async attachMapper(entry) {
160213
+ async attachMapper(inst, entry) {
159729
160214
  const factory = getMapperFactory(entry.mapperKind);
159730
160215
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
159731
160216
  const mapper = await factory({
@@ -159733,6 +160218,7 @@ var ExportHapAddon = class extends BaseAddon {
159733
160218
  deviceId: entry.deviceId,
159734
160219
  displayName: entry.displayName,
159735
160220
  options: {
160221
+ instanceId: inst.id,
159736
160222
  decodeMemos: this.decodeMemos,
159737
160223
  resolveFfmpeg: this.pinnedFfmpeg,
159738
160224
  hksvClipStore: this.hksvClipStore,
@@ -159752,29 +160238,29 @@ var ExportHapAddon = class extends BaseAddon {
159752
160238
  useBridge: entry.settings?.useBridge
159753
160239
  });
159754
160240
  for (const accessory of mapper.accessories) {
159755
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160241
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
159756
160242
  await publishStandalone(accessory, {
159757
- pincode: this.pincode,
160243
+ pincode: inst.pincode,
159758
160244
  port: 0,
159759
160245
  bind: this.bind,
159760
160246
  logger: this.ctx.logger
159761
160247
  });
159762
160248
  }
159763
- this.exposed.set(entry.deviceId, mapper);
160249
+ inst.exposed.set(entry.deviceId, mapper);
159764
160250
  return { childAccessoryUuids: [] };
159765
160251
  }
159766
- async detachMapper(deviceId) {
159767
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160252
+ async detachMapper(inst, deviceId) {
160253
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
159768
160254
  if (pendingTimer) {
159769
160255
  clearTimeout(pendingTimer);
159770
- this.pendingRebuildTimers.delete(deviceId);
160256
+ inst.pendingRebuildTimers.delete(deviceId);
159771
160257
  }
159772
- const mapper = this.exposed.get(deviceId);
160258
+ const mapper = inst.exposed.get(deviceId);
159773
160259
  if (!mapper) return;
159774
- this.exposed.delete(deviceId);
160260
+ inst.exposed.delete(deviceId);
159775
160261
  for (const accessory of mapper.accessories) {
159776
- if (this.bridgeHost?.holds(accessory) === true) {
159777
- this.bridgeHost.remove(accessory);
160262
+ if (inst.bridgeHost.holds(accessory)) {
160263
+ inst.bridgeHost.remove(accessory);
159778
160264
  continue;
159779
160265
  }
159780
160266
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -159783,21 +160269,22 @@ var ExportHapAddon = class extends BaseAddon {
159783
160269
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
159784
160270
  });
159785
160271
  }
159786
- requireActionExports() {
159787
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
159788
- return this.actionExports;
160272
+ requireActionExports(inst) {
160273
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160274
+ return inst.actionExports;
159789
160275
  }
159790
- async detachAll() {
159791
- const ids = Array.from(this.exposed.keys());
159792
- for (const id of ids) await this.detachMapper(id);
160276
+ async detachAll(inst) {
160277
+ const ids = Array.from(inst.exposed.keys());
160278
+ for (const id of ids) await this.detachMapper(inst, id);
159793
160279
  }
159794
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
159795
- * on detach so stale timers can't republish a removed accessory. */
159796
- pendingRebuildTimers = /* @__PURE__ */ new Map();
159797
160280
  /** Deterministic HAP accessory UUID for a device — the same one the
159798
160281
  * orchestrator built it with (`mappers/kind.ts`). */
159799
- hapAccessoryUuid(deviceId) {
159800
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160282
+ hapAccessoryUuid(inst, deviceId) {
160283
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160284
+ }
160285
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160286
+ syncStateOf(inst) {
160287
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
159801
160288
  }
159802
160289
  /**
159803
160290
  * Export fingerprint of a device from its PERSISTED features + type
@@ -159815,7 +160302,7 @@ var ExportHapAddon = class extends BaseAddon {
159815
160302
  * A brand-new un-probed device with no persisted entry falls back to its
159816
160303
  * fresh fingerprint (publishes once, acceptable).
159817
160304
  */
159818
- async computeExportFingerprint(deviceId) {
160305
+ async computeExportFingerprint(inst, deviceId) {
159819
160306
  try {
159820
160307
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
159821
160308
  if (!device) return null;
@@ -159824,10 +160311,10 @@ var ExportHapAddon = class extends BaseAddon {
159824
160311
  deviceType: device.type,
159825
160312
  features: device.features
159826
160313
  });
159827
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160314
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
159828
160315
  const withToken = withRecordabilityToken({
159829
160316
  base: fresh,
159830
- token: await this.readRecordabilityToken(deviceId, device.type),
160317
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
159831
160318
  persisted
159832
160319
  });
159833
160320
  return resolveExportFingerprint({
@@ -159847,12 +160334,12 @@ var ExportHapAddon = class extends BaseAddon {
159847
160334
  * republish every non-camera accessory once for nothing) and for a camera
159848
160335
  * whose profiles could not be read right now.
159849
160336
  */
159850
- async readRecordabilityToken(deviceId, type) {
160337
+ async readRecordabilityToken(inst, deviceId, type) {
159851
160338
  if (pickMapperKind(type) !== "camera") return null;
159852
160339
  try {
159853
160340
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
159854
160341
  return recordabilityTokenFor({
159855
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160342
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
159856
160343
  entries: entries ?? null
159857
160344
  });
159858
160345
  } catch {
@@ -159861,20 +160348,20 @@ var ExportHapAddon = class extends BaseAddon {
159861
160348
  }
159862
160349
  /** Persist a device's current export fingerprint into `exportSyncState`
159863
160350
  * (best-effort; called after a successful attach). */
159864
- async persistFingerprint(deviceId, fingerprint) {
159865
- const state = syncStateFromJson(this.config.exportSyncState);
160351
+ async persistFingerprint(inst, deviceId, fingerprint) {
160352
+ const state = this.syncStateOf(inst);
159866
160353
  state.set(deviceId, {
159867
160354
  fingerprint,
159868
- externalIds: [this.hapAccessoryUuid(deviceId)]
160355
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
159869
160356
  });
159870
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160357
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159871
160358
  }
159872
160359
  /** Drop a device's `exportSyncState` entry (on unexpose). */
159873
- async forgetFingerprint(deviceId) {
159874
- const state = syncStateFromJson(this.config.exportSyncState);
160360
+ async forgetFingerprint(inst, deviceId) {
160361
+ const state = this.syncStateOf(inst);
159875
160362
  if (!state.has(deviceId)) return;
159876
160363
  state.delete(deviceId);
159877
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160364
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159878
160365
  }
159879
160366
  /**
159880
160367
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -159905,34 +160392,23 @@ var ExportHapAddon = class extends BaseAddon {
159905
160392
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
159906
160393
  if (deviceIdNumeric === null) return;
159907
160394
  const deviceId = String(deviceIdNumeric);
159908
- if (!this.findEntry(deviceIdNumeric)) return;
159909
- const existing = this.pendingRebuildTimers.get(deviceId);
159910
- if (existing) clearTimeout(existing);
159911
- const timer = setTimeout(() => {
159912
- this.pendingRebuildTimers.delete(deviceId);
159913
- this.reconcileDevice(deviceId);
159914
- }, 500);
159915
- if (typeof timer.unref === "function") timer.unref();
159916
- this.pendingRebuildTimers.set(deviceId, timer);
160395
+ for (const inst of this.bridges.values()) {
160396
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160397
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160398
+ if (existing) clearTimeout(existing);
160399
+ const timer = setTimeout(() => {
160400
+ inst.pendingRebuildTimers.delete(deviceId);
160401
+ this.reconcileDevice(inst, deviceId);
160402
+ }, 500);
160403
+ if (typeof timer.unref === "function") timer.unref();
160404
+ inst.pendingRebuildTimers.set(deviceId, timer);
160405
+ }
159917
160406
  });
159918
160407
  this.ctx.addDisposer(async () => {
159919
160408
  unsubscribe();
159920
160409
  });
159921
160410
  }
159922
160411
  /**
159923
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
159924
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
159925
- * per-device timers into `pendingRebuildTimers` but never clear the map on
159926
- * their own teardown — that shared resource is cleared here, exactly once, on
159927
- * shutdown.
159928
- */
159929
- disposeSharedRebuildTimers() {
159930
- this.ctx.addDisposer(async () => {
159931
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
159932
- this.pendingRebuildTimers.clear();
159933
- });
159934
- }
159935
- /**
159936
160412
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
159937
160413
  * its persisted export shape changes. `DeviceProvisioned` is gated by
159938
160414
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -159962,22 +160438,22 @@ var ExportHapAddon = class extends BaseAddon {
159962
160438
  * Errors are logged and swallowed — a failed reconcile leaves the prior
159963
160439
  * accessory up, which is strictly better than removing it.
159964
160440
  */
159965
- async reconcileDevice(deviceId) {
160441
+ async reconcileDevice(inst, deviceId) {
159966
160442
  const numericId = Number.parseInt(deviceId, 10);
159967
160443
  if (!Number.isFinite(numericId)) return;
159968
- const entry = this.findEntry(numericId);
160444
+ const entry = inst.findEntry(numericId);
159969
160445
  if (!entry) return;
159970
160446
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159971
- const current = await this.computeExportFingerprint(numericId);
160447
+ const current = await this.computeExportFingerprint(inst, numericId);
159972
160448
  if (current === null) {
159973
160449
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
159974
160450
  return;
159975
160451
  }
159976
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160452
+ const last = this.syncStateOf(inst).get(numericId);
159977
160453
  if (last?.fingerprint === current) {
159978
- if (!this.exposed.has(deviceId)) try {
159979
- await this.attachMapper(entry);
159980
- await this.persistFingerprint(numericId, current);
160454
+ if (!inst.exposed.has(deviceId)) try {
160455
+ await this.attachMapper(inst, entry);
160456
+ await this.persistFingerprint(inst, numericId, current);
159981
160457
  } catch (err) {
159982
160458
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
159983
160459
  }
@@ -159989,9 +160465,9 @@ var ExportHapAddon = class extends BaseAddon {
159989
160465
  to: current.slice(0, 12)
159990
160466
  } });
159991
160467
  try {
159992
- await this.detachMapper(deviceId);
159993
- await this.attachMapper(entry);
159994
- await this.persistFingerprint(numericId, current);
160468
+ await this.detachMapper(inst, deviceId);
160469
+ await this.attachMapper(inst, entry);
160470
+ await this.persistFingerprint(inst, numericId, current);
159995
160471
  } catch (err) {
159996
160472
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
159997
160473
  }
@@ -160054,7 +160530,7 @@ var ExportHapAddon = class extends BaseAddon {
160054
160530
  return null;
160055
160531
  }
160056
160532
  }
160057
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160533
+ /** The one declaration of the bind-interface field: a fact of one node. */
160058
160534
  interfaceNameField() {
160059
160535
  return this.field({
160060
160536
  type: "text",
@@ -160074,10 +160550,26 @@ var ExportHapAddon = class extends BaseAddon {
160074
160550
  fields: [this.interfaceNameField()]
160075
160551
  }] }) : null;
160076
160552
  }
160553
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160554
+ async deviceDefaultsSchema(cap) {
160555
+ return cap === "device-export" ? this.schema({ sections: [{
160556
+ id: "export-hap-defaults",
160557
+ title: "HomeKit Export",
160558
+ fields: [this.field({
160559
+ type: "number",
160560
+ key: "clipRetentionDays",
160561
+ label: "Keep HomeKit clips for (days)",
160562
+ 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.",
160563
+ default: DEFAULT_CONFIG.clipRetentionDays,
160564
+ placement: { tab: "advanced" }
160565
+ })]
160566
+ }] }) : null;
160567
+ }
160077
160568
  /**
160078
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
160079
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
160080
- * value the migration wrote.
160569
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160570
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160571
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160572
+ * config when anything landed, so this boot binds the value the migration wrote.
160081
160573
  */
160082
160574
  async migrateSettings() {
160083
160575
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
@@ -160087,47 +160579,15 @@ var ExportHapAddon = class extends BaseAddon {
160087
160579
  ...this.exposureMigrationPorts()
160088
160580
  }))).applied.length > 0) await this.resolveConfig();
160089
160581
  }
160090
- globalSettingsSchema() {
160091
- return this.schema({ sections: [{
160092
- id: "export-hap",
160093
- title: "HomeKit Export",
160094
- 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.",
160095
- columns: 1,
160096
- fields: [
160097
- this.field({
160098
- type: "text",
160099
- key: "bridgeName",
160100
- label: "Installation name",
160101
- 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.",
160102
- default: DEFAULT_CONFIG.bridgeName,
160103
- requiresRestart: true,
160104
- placement: { tab: "advanced" }
160105
- }),
160106
- this.field({
160107
- type: "password",
160108
- key: "fixedPin",
160109
- label: "Fixed setup code (XXX-XX-XXX)",
160110
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
160111
- default: DEFAULT_CONFIG.fixedPin,
160112
- requiresRestart: true,
160113
- placement: { tab: "advanced" }
160114
- }),
160115
- this.interfaceNameField(),
160116
- this.field({
160117
- type: "number",
160118
- key: "clipRetentionDays",
160119
- label: "Keep HomeKit clips for (days)",
160120
- 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.",
160121
- default: DEFAULT_CONFIG.clipRetentionDays,
160122
- placement: { tab: "advanced" }
160123
- })
160124
- ]
160125
- }] });
160582
+ scopedSettingsCapabilities() {
160583
+ return ["device-export"];
160126
160584
  }
160127
160585
  async buildDeviceSettingsContribution(deviceId) {
160128
160586
  const kind = await this.resolveExportKind(deviceId);
160129
160587
  if (kind === null) return null;
160130
- const entry = this.findEntry(deviceId);
160588
+ const inst = this.instanceForDevice(deviceId);
160589
+ if (inst === null) return null;
160590
+ const entry = inst.findEntry(deviceId);
160131
160591
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
160132
160592
  const enabled = entry !== null;
160133
160593
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -160137,13 +160597,13 @@ var ExportHapAddon = class extends BaseAddon {
160137
160597
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
160138
160598
  const keepClipsKey = `hap:${deviceId}:keepClips`;
160139
160599
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
160140
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160600
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
160141
160601
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
160142
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160602
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
160143
160603
  const name = entry?.displayName ?? `Device ${deviceId}`;
160144
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
160145
- 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}.`;
160146
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160604
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160605
+ 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}.`;
160606
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
160147
160607
  let qrValue = "";
160148
160608
  if (qrSource) try {
160149
160609
  qrValue = qrSource.setupURI();
@@ -160185,7 +160645,7 @@ var ExportHapAddon = class extends BaseAddon {
160185
160645
  type: "info",
160186
160646
  key: `hap:${deviceId}:hksvRecordingStatus`,
160187
160647
  label: "HomeKit recording (Secure Video)",
160188
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160648
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160189
160649
  showWhen: {
160190
160650
  field: enabledKey,
160191
160651
  equals: true
@@ -160269,7 +160729,7 @@ var ExportHapAddon = class extends BaseAddon {
160269
160729
  type: "qr-code",
160270
160730
  key: "__hap-pair-qr",
160271
160731
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
160272
- 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}.`,
160732
+ 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}.`,
160273
160733
  value: qrValue,
160274
160734
  size: 192,
160275
160735
  alt: `HomeKit pairing QR for ${name}`,
@@ -160308,8 +160768,10 @@ var ExportHapAddon = class extends BaseAddon {
160308
160768
  async applyDeviceSettingsPatch(deviceId, patch) {
160309
160769
  const deviceIdStr = String(deviceId);
160310
160770
  const log = this.ctx.logger.withTags({ deviceId });
160311
- const current = this.findEntry(deviceId);
160312
- const wasEnabled = this.exposed.has(deviceIdStr);
160771
+ const inst = this.instanceForDevice(deviceId);
160772
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160773
+ const current = inst.findEntry(deviceId);
160774
+ const wasEnabled = inst.exposed.has(deviceIdStr);
160313
160775
  const enabledKey = `hap:${deviceId}:enabled`;
160314
160776
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
160315
160777
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -160338,12 +160800,12 @@ var ExportHapAddon = class extends BaseAddon {
160338
160800
  clipRetentionDays
160339
160801
  };
160340
160802
  if (!enabledValue) {
160341
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160803
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
160342
160804
  return { success: true };
160343
160805
  }
160344
160806
  if (!wasEnabled) {
160345
- await this.exposeDevice(deviceIdStr);
160346
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160807
+ await this.exposeDevice(inst, deviceIdStr);
160808
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160347
160809
  return { success: true };
160348
160810
  }
160349
160811
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -160357,7 +160819,7 @@ var ExportHapAddon = class extends BaseAddon {
160357
160819
  mapperKind,
160358
160820
  useBridge
160359
160821
  });
160360
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160822
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160361
160823
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
160362
160824
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
160363
160825
  streamPreference: {
@@ -160374,8 +160836,8 @@ var ExportHapAddon = class extends BaseAddon {
160374
160836
  }
160375
160837
  } });
160376
160838
  try {
160377
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
160378
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160839
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160840
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
160379
160841
  } catch (err) {
160380
160842
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
160381
160843
  }
@@ -160437,35 +160899,38 @@ var ExportHapAddon = class extends BaseAddon {
160437
160899
  exposureHandle() {
160438
160900
  return this.requireRecords().kind(hapBridgeExportsKind);
160439
160901
  }
160440
- /** Load the default instance's exposure record; create it empty when none exists. */
160441
- async loadExposure() {
160902
+ /** Load a bridge's exposure record; create it empty when none exists. */
160903
+ async loadExposure(id) {
160442
160904
  const handle = this.exposureHandle();
160443
- const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160444
- if (row !== null) {
160445
- this.exposure = row.data;
160446
- return;
160447
- }
160905
+ const row = await handle.get(id);
160906
+ if (row !== null) return row.data;
160907
+ const empty = {
160908
+ name: HAP_EXPOSURE_NAME,
160909
+ devices: [],
160910
+ actions: []
160911
+ };
160448
160912
  await handle.put({
160449
- id: HAP_DEFAULT_INSTANCE_ID,
160450
- data: this.exposure
160913
+ id,
160914
+ data: empty
160451
160915
  }, { ifRev: 0 });
160916
+ return empty;
160452
160917
  }
160453
- async writeExposure(next) {
160918
+ async writeExposure(inst, next) {
160454
160919
  await this.exposureHandle().put({
160455
- id: HAP_DEFAULT_INSTANCE_ID,
160920
+ id: inst.id,
160456
160921
  data: next
160457
160922
  });
160458
- this.exposure = next;
160923
+ inst.exposure = next;
160459
160924
  }
160460
- setExposedDevices(devices) {
160461
- return this.writeExposure({
160462
- ...this.exposure,
160925
+ setExposedDevices(inst, devices) {
160926
+ return this.writeExposure(inst, {
160927
+ ...inst.exposure,
160463
160928
  devices
160464
160929
  });
160465
160930
  }
160466
- setExposedActions(actions) {
160467
- return this.writeExposure({
160468
- ...this.exposure,
160931
+ setExposedActions(inst, actions) {
160932
+ return this.writeExposure(inst, {
160933
+ ...inst.exposure,
160469
160934
  actions
160470
160935
  });
160471
160936
  }
@@ -160489,20 +160954,16 @@ var ExportHapAddon = class extends BaseAddon {
160489
160954
  readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160490
160955
  };
160491
160956
  }
160492
- findEntry(deviceId) {
160493
- const id = String(deviceId);
160494
- return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
160495
- }
160496
- async updateEntrySettings(deviceIdStr, settings) {
160497
- const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160957
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160958
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160498
160959
  ...e,
160499
160960
  settings
160500
160961
  } : e);
160501
- await this.setExposedDevices(next);
160962
+ await this.setExposedDevices(inst, next);
160502
160963
  }
160503
160964
  };
160504
160965
  function errMsg(err) {
160505
160966
  return err instanceof Error ? err.message : String(err);
160506
160967
  }
160507
160968
  //#endregion
160508
- export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };
160969
+ export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, exportHapActions as a, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };