@camstack/addon-export-hap 1.2.192 → 1.2.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,8 +36,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
36
36
  }) : target, mod));
37
37
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
  //#endregion
39
- let node_child_process = require("node:child_process");
40
39
  let node_crypto = require("node:crypto");
40
+ let node_child_process = require("node:child_process");
41
41
  let node_path = require("node:path");
42
42
  __toESM(node_path, 1);
43
43
  node_path = __toESM(node_path);
@@ -6031,7 +6031,7 @@ var ZodIssueCode = {
6031
6031
  var ZodFirstPartyTypeKind;
6032
6032
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6033
6033
  //#endregion
6034
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6034
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
6035
6035
  /**
6036
6036
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6037
6037
  * window to float samples (D455).
@@ -6631,7 +6631,7 @@ var NOT_RUN = {
6631
6631
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6632
6632
  * because the hub (and this addon's boot) must not hang on a migration.
6633
6633
  */
6634
- async function runAddonMigrations(host, migrations, logger) {
6634
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6635
6635
  const first = migrations[0];
6636
6636
  if (first === void 0) return NOT_RUN;
6637
6637
  const owner = first.meta.owner;
@@ -6660,7 +6660,9 @@ async function runAddonMigrations(host, migrations, logger) {
6660
6660
  else if (status === "blocked") blocked.push(id);
6661
6661
  else skipped.push(id);
6662
6662
  };
6663
+ const selected = options.only === void 0 ? null : new Set(options.only);
6663
6664
  for (const step of declaration.steps) {
6665
+ if (selected !== null && !selected.has(step.id)) continue;
6664
6666
  const bound = byId.get(step.id);
6665
6667
  if (bound === void 0 || step.action === "skip") {
6666
6668
  skipped.push(step.id);
@@ -7820,14 +7822,18 @@ var BaseAddon = class {
7820
7822
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7821
7823
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7822
7824
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7825
+ *
7826
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7827
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7828
+ * omitted applied ids "newer").
7823
7829
  */
7824
- async runMigrations(migrations) {
7830
+ async runMigrations(migrations, options) {
7825
7831
  const api = this.ctx.api.migrations;
7826
7832
  const report = await runAddonMigrations({
7827
7833
  declareOwner: (input) => api.declareOwner.mutate(input),
7828
7834
  startMigration: (input) => api.startMigration.mutate(input),
7829
7835
  finishMigration: (input) => api.finishMigration.mutate(input)
7830
- }, migrations, this.ctx.logger);
7836
+ }, migrations, this.ctx.logger, options);
7831
7837
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7832
7838
  return report;
7833
7839
  }
@@ -9285,6 +9291,7 @@ function defineEntryKind(name, spec) {
9285
9291
  class: "config",
9286
9292
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9287
9293
  retention: { none: "an entry goes only when the operator deletes it" },
9294
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9288
9295
  ...spec.database === void 0 ? {} : { database: spec.database },
9289
9296
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9290
9297
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -9981,6 +9988,28 @@ function toNodeId(idOrRunnerId) {
9981
9988
  const head = idOrRunnerId.split("/")[0];
9982
9989
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9983
9990
  }
9991
+ /**
9992
+ * Identity — preserves literal types for downstream inference.
9993
+ *
9994
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9995
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9996
+ * the broader unions declared on `CustomActionSpec`'s default generics.
9997
+ * Shape validity is enforced separately by the `customAction(...)` helper
9998
+ * whose return type is already a `CustomActionSpec<...>`.
9999
+ */
10000
+ function defineCustomActions(spec) {
10001
+ return spec;
10002
+ }
10003
+ function customAction(input, output, options) {
10004
+ return {
10005
+ input,
10006
+ output,
10007
+ kind: options?.kind ?? "query",
10008
+ auth: options?.auth ?? "protected",
10009
+ scope: options?.scope ?? { kind: "system" },
10010
+ ...options?.caller ? { caller: "required" } : {}
10011
+ };
10012
+ }
9984
10013
  Object.freeze({ "doorbell": "lastPressedAt" });
9985
10014
  /** Every capability name, so addon code can check a name without the schema graph. */
9986
10015
  var CAP_NAMES = Object.freeze([
@@ -12009,7 +12038,7 @@ object({
12009
12038
  params: record(string(), union([string(), number()])).optional()
12010
12039
  });
12011
12040
  //#endregion
12012
- //#region ../types/dist/composition-CRNwcFYY.mjs
12041
+ //#region ../types/dist/composition-pOHbTzRB.mjs
12013
12042
  var AUDIO_ENCODER_BY_CODEC = {
12014
12043
  opus: "libopus",
12015
12044
  aac: "aac",
@@ -15266,7 +15295,13 @@ var MigrationLedgerEntrySchema = object({
15266
15295
  * joined by the engine from the catalogues it knows this boot. Absent when no
15267
15296
  * catalogue lists the id (a newer database).
15268
15297
  */
15269
- meta: MigrationMetaSchema.optional()
15298
+ meta: MigrationMetaSchema.optional(),
15299
+ /**
15300
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15301
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15302
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15303
+ */
15304
+ ownerNotLoaded: boolean().optional()
15270
15305
  });
15271
15306
  /** A catalogued migration that is not applied, with where it stands. */
15272
15307
  var MigrationPendingEntrySchema = object({
@@ -50014,6 +50049,9 @@ var RunningProposalEvidenceSchema = object({
50014
50049
  runsFound: number().int().nonnegative(),
50015
50050
  pausesFound: number().int().nonnegative(),
50016
50051
  longestPauseMs: number().nonnegative(),
50052
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50053
+ pulsesFound: number().int().nonnegative(),
50054
+ longestPulseMs: number().nonnegative(),
50017
50055
  idleFloorW: number(),
50018
50056
  noiseCeilingW: number(),
50019
50057
  plateauW: number(),
@@ -51240,13 +51278,6 @@ var ExportInstanceUnknownError = class extends Error {
51240
51278
  function statusInstanceOf(input) {
51241
51279
  return "instanceId" in input ? input.instanceId : void 0;
51242
51280
  }
51243
- /**
51244
- * A single-instance provider's check: an absent id or its own passes, any other throws
51245
- * `ExportInstanceUnknownError`.
51246
- */
51247
- function assertOwnExportInstance(addon, own, instanceId) {
51248
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51249
- }
51250
51281
  var LinkStateSchema = _enum([
51251
51282
  "unlinked",
51252
51283
  "linked",
@@ -55098,6 +55129,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
55098
55129
  }), object({ success: boolean() }), {
55099
55130
  kind: "mutation",
55100
55131
  auth: "admin"
55132
+ }), method(object({ id: string() }), object({
55133
+ rows: number().int().nonnegative(),
55134
+ secrets: number().int().nonnegative()
55135
+ }), {
55136
+ kind: "mutation",
55137
+ auth: "admin"
55101
55138
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
55102
55139
  addonId: string(),
55103
55140
  settings: record(string(), unknown())
@@ -77197,11 +77234,15 @@ discriminatedUnion("kind", [object({
77197
77234
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77198
77235
  * near F. A device that is not near one level most of the time has no floor.
77199
77236
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77200
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77201
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77237
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77238
+ * display waking): it is neither a run nor a pause. Among the remaining
77239
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77240
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77241
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77242
+ * is no run.
77202
77243
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77203
- * grid a person would type; stop dwell covers the longest pause; start dwell
77204
- * covers the longest standby blip above T.
77244
+ * grid a person would type; stop dwell covers the longest pause and the
77245
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
77205
77246
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77206
77247
  * run must hold exactly one true interval and nothing may flap outside.
77207
77248
  */
@@ -77212,6 +77253,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
77212
77253
  30 * SECOND_MS;
77213
77254
  60 * SECOND_MS;
77214
77255
  20 * MINUTE_MS$1;
77256
+ 90 * SECOND_MS;
77257
+ 30 * MINUTE_MS$1;
77258
+ 10 * MINUTE_MS$1;
77259
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
77215
77260
  10 * SECOND_MS;
77216
77261
  10 * SECOND_MS;
77217
77262
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80932,6 +80977,13 @@ Object.freeze({
80932
80977
  access: "create",
80933
80978
  role: "admin"
80934
80979
  },
80980
+ "integrations.clearSettings": {
80981
+ capName: "integrations",
80982
+ capScope: "system",
80983
+ addonId: null,
80984
+ access: "delete",
80985
+ role: "admin"
80986
+ },
80935
80987
  "integrations.create": {
80936
80988
  capName: "integrations",
80937
80989
  capScope: "system",
@@ -92250,6 +92302,17 @@ object({
92250
92302
  delay: number().nonnegative().optional(),
92251
92303
  commands: record(string(), unknown())
92252
92304
  });
92305
+ //#endregion
92306
+ //#region src/custom-actions.ts
92307
+ /**
92308
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92309
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92310
+ * because it unpairs every controller of the bridge.
92311
+ */
92312
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92313
+ kind: "mutation",
92314
+ auth: "admin"
92315
+ }) });
92253
92316
  process.platform, process.env["SystemRoot"];
92254
92317
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
92255
92318
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -139149,14 +139212,60 @@ function clearPairingFiles(accessoryUuid, logger) {
139149
139212
  } });
139150
139213
  }
139151
139214
  }
139215
+ //#endregion
139216
+ //#region src/hap-instance-kinds.ts
139217
+ /**
139218
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139219
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139220
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139221
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139222
+ * (`hapPersistDirOf`). The default instance is keyed by the
139223
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139224
+ * controller that paired before keeps working.
139225
+ */
139226
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139227
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139228
+ /**
139229
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139230
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139231
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139232
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139233
+ */
139234
+ function instanceSalt(instanceId) {
139235
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139236
+ }
139237
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139238
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139239
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139240
+ function hapPersistDirOf(instanceId) {
139241
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139242
+ }
139243
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139244
+ title: "HomeKit bridge",
139245
+ nameField: "name",
139246
+ schema: object({
139247
+ name: string().min(1),
139248
+ username: string().min(1),
139249
+ uuid: string().min(1),
139250
+ pincode: string().min(1).meta({ secret: true }),
139251
+ enabled: boolean().optional()
139252
+ })
139253
+ });
139254
+ function identityOfBody(body) {
139255
+ return {
139256
+ username: body.username,
139257
+ uuid: body.uuid,
139258
+ pincode: body.pincode
139259
+ };
139260
+ }
139152
139261
  /** Deterministic and distinct from every device accessory uuid. */
139153
- function actionSwitchUuid(actionId) {
139154
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139262
+ function actionSwitchUuid(actionId, instanceId) {
139263
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
139155
139264
  }
139156
139265
  function buildActionSwitch(input) {
139157
139266
  const { actionId, displayName, run } = input;
139158
139267
  const autoOffMs = input.autoOffMs ?? 1e3;
139159
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139268
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
139160
139269
  accessory.category = import_dist.Categories.SWITCH;
139161
139270
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
139162
139271
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -139230,6 +139339,10 @@ var ActionExports = class {
139230
139339
  exposedAs: e.displayName
139231
139340
  }));
139232
139341
  }
139342
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139343
+ accessoryUuids() {
139344
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139345
+ }
139233
139346
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
139234
139347
  async attachAll() {
139235
139348
  for (const entry of this.entries) try {
@@ -139297,6 +139410,7 @@ var ActionExports = class {
139297
139410
  const mapper = buildActionSwitch({
139298
139411
  actionId: entry.actionId,
139299
139412
  displayName: entry.displayName,
139413
+ instanceId: this.ports.instanceId,
139300
139414
  run: async () => {
139301
139415
  await runExportedAction(this.ports.api, this.ports.logger, {
139302
139416
  exporter: EXPORTER,
@@ -139437,6 +139551,128 @@ var BridgeHost = class {
139437
139551
  }
139438
139552
  };
139439
139553
  //#endregion
139554
+ //#region src/mappers/kind.ts
139555
+ /**
139556
+ * Which orchestrator a device gets, which device types the picker offers, and
139557
+ * what a device's HomeKit accessory is called on the wire.
139558
+ *
139559
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139560
+ * import the uuid convention without importing the registry that imports them.
139561
+ */
139562
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139563
+ /**
139564
+ * The device types the Export picker offers, and the answer to the cap's
139565
+ * `listSupportedDeviceKinds`.
139566
+ *
139567
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139568
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139569
+ * doctrine the HA exporter writes down, and the thing that confined the
139570
+ * previous exporter to cameras when it was ignored.
139571
+ *
139572
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139573
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139574
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139575
+ * absent — each needs a service whose semantics the table cannot yet honour,
139576
+ * and offering the tab before the mapping exists is how an operator gets an
139577
+ * accessory that pairs and does nothing.
139578
+ *
139579
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139580
+ * (`builders/generic/security-system.ts`), and the two things the table could
139581
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139582
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139583
+ * refuses the write out loud instead of pretending to arm.
139584
+ */
139585
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139586
+ DeviceType.Camera,
139587
+ DeviceType.Light,
139588
+ DeviceType.Switch,
139589
+ DeviceType.Siren,
139590
+ DeviceType.Sensor,
139591
+ DeviceType.Lock,
139592
+ DeviceType.Presence,
139593
+ DeviceType.AlarmPanel,
139594
+ DeviceType.Generic
139595
+ ];
139596
+ /**
139597
+ * Resolve the orchestrator for a device from its TYPE.
139598
+ *
139599
+ * `null` means "no Export tab": the picker must not offer a type no
139600
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139601
+ * to `camera` — that is what every entry persisted before this function existed
139602
+ * carries, and a transient API failure must never re-shape an exposed camera.
139603
+ */
139604
+ function pickMapperKind(deviceType) {
139605
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139606
+ if (deviceType === DeviceType.Camera) return "camera";
139607
+ const withheld = applianceExport("homekit", deviceType);
139608
+ if (withheld !== null && !withheld.exported) return null;
139609
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139610
+ }
139611
+ /**
139612
+ * The deterministic HAP accessory UUID for a device.
139613
+ *
139614
+ * One function, because three call sites depend on the answer agreeing: the
139615
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139616
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139617
+ * and the export sync state that records it.
139618
+ *
139619
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139620
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139621
+ * would make every paired camera a stranger. Generic devices get their own
139622
+ * namespace so a switch and a camera that happen to share a device id are not
139623
+ * the same HomeKit accessory.
139624
+ */
139625
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139626
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139627
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139628
+ }
139629
+ //#endregion
139630
+ //#region src/bridge-instance.ts
139631
+ var BridgeInstance = class {
139632
+ id;
139633
+ name;
139634
+ identity;
139635
+ bridgeHost;
139636
+ exposure;
139637
+ /** The devices of this bridge that have a live accessory, by device id. */
139638
+ exposed = /* @__PURE__ */ new Map();
139639
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139640
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139641
+ actionExports = null;
139642
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139643
+ syncState = /* @__PURE__ */ new Map();
139644
+ constructor(id, name, identity, bridgeHost, exposure) {
139645
+ this.id = id;
139646
+ this.name = name;
139647
+ this.identity = identity;
139648
+ this.bridgeHost = bridgeHost;
139649
+ this.exposure = exposure;
139650
+ }
139651
+ get pincode() {
139652
+ return this.identity.pincode;
139653
+ }
139654
+ findEntry(deviceId) {
139655
+ const id = String(deviceId);
139656
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139657
+ }
139658
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139659
+ accessoryUuidOf(kind, deviceId) {
139660
+ return accessoryUuidFor(kind, deviceId, this.id);
139661
+ }
139662
+ /**
139663
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139664
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139665
+ */
139666
+ pairingUuids() {
139667
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139668
+ return [
139669
+ this.identity.uuid,
139670
+ ...fromDevices,
139671
+ ...this.actionExports?.accessoryUuids() ?? []
139672
+ ];
139673
+ }
139674
+ };
139675
+ //#endregion
139440
139676
  //#region src/exposed-entry.ts
139441
139677
  /**
139442
139678
  * Carrying an exposed-device entry across a re-expose.
@@ -139523,81 +139759,31 @@ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139523
139759
  /** The settings keys that moved into the record; the migrations name them. */
139524
139760
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139525
139761
  //#endregion
139526
- //#region src/hap-instance-kinds.ts
139527
- /**
139528
- * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139529
- * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139530
- * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139531
- * the row). The directory its pairing state lives in is derived from the id, never stored
139532
- * (`hapPersistDirOf`). The default instance is keyed by the
139533
- * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139534
- * controller that paired before keeps working.
139535
- */
139536
- /** The default instance keeps its record under the addon id (it adopted the old identity). */
139537
- var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139538
- /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139539
- var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139540
- /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139541
- function hapPersistDirOf(instanceId) {
139542
- return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139543
- }
139544
- var hapBridgesKind = defineEntryKind("hap-bridges", {
139545
- title: "HomeKit bridge",
139546
- nameField: "name",
139547
- schema: object({
139548
- name: string().min(1),
139549
- username: string().min(1),
139550
- uuid: string().min(1),
139551
- pincode: string().min(1).meta({ secret: true }),
139552
- enabled: boolean().optional()
139553
- })
139554
- });
139555
- function identityOfBody(body) {
139556
- return {
139557
- username: body.username,
139558
- uuid: body.uuid,
139559
- pincode: body.pincode
139560
- };
139561
- }
139562
- //#endregion
139563
139762
  //#region src/hap-identity.ts
139564
139763
  /**
139565
- * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139566
- * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139567
- * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139568
- * A legacy identity without a record means the migration did not finish, and minting then would
139569
- * unpair every controller, so the addon refuses to boot with the reason.
139764
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139765
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139766
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139767
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139768
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139769
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139770
+ *
139771
+ * Every other instance is read as it is stored; this module is only about the default one.
139570
139772
  */
139571
- /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139572
- async function resolveBridgeIdentity(fixedPin, ports) {
139773
+ async function resolveDefaultBridge(ports) {
139573
139774
  const stored = await ports.readRecord();
139574
139775
  if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139575
- if (stored.kind === "resolved") {
139576
- if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139577
- await ports.patchPincode(fixedPin);
139578
- return {
139579
- identity: identityOfBody({
139580
- ...stored.body,
139581
- pincode: fixedPin
139582
- }),
139583
- minted: false
139584
- };
139585
- }
139586
- return {
139587
- identity: identityOfBody(stored.body),
139588
- minted: false
139589
- };
139590
- }
139591
- if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139592
- const fresh = ports.mint();
139593
- const body = fixedPin === null ? fresh : {
139594
- ...fresh,
139595
- pincode: fixedPin
139776
+ if (stored.kind === "resolved") return {
139777
+ kind: "existing",
139778
+ identity: identityOfBody(stored.body)
139596
139779
  };
139780
+ if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139781
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139782
+ const body = ports.mint();
139597
139783
  await ports.putFresh(body);
139598
139784
  return {
139599
- identity: identityOfBody(body),
139600
- minted: true
139785
+ kind: "minted",
139786
+ identity: identityOfBody(body)
139601
139787
  };
139602
139788
  }
139603
139789
  //#endregion
@@ -139824,12 +140010,87 @@ function legacyIdentityOf(value) {
139824
140010
  };
139825
140011
  }
139826
140012
  //#endregion
140013
+ //#region src/migrations/bridge-name-to-instance.ts
140014
+ async function moveBridgeNameToInstance(ports) {
140015
+ const name = (await ports.readBridgeName()).trim();
140016
+ if (name === "") return {
140017
+ outcome: "already-done",
140018
+ summary: { renamed: false }
140019
+ };
140020
+ const held = await ports.readDefaultRecord();
140021
+ if (held === null || held.name === name) return {
140022
+ outcome: "already-done",
140023
+ summary: { renamed: false }
140024
+ };
140025
+ await ports.patchDefaultName(name);
140026
+ const after = await ports.readDefaultRecord();
140027
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140028
+ return {
140029
+ outcome: "done",
140030
+ summary: { renamed: true }
140031
+ };
140032
+ }
140033
+ //#endregion
140034
+ //#region src/migrations/drop-global-knobs.ts
140035
+ /**
140036
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140037
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140038
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140039
+ * fact of one node, which the node row carries since the per-node migration.
140040
+ *
140041
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140042
+ * keychain value would be orphaned otherwise):
140043
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140044
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140045
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140046
+ * can never lose the value. A `@<nodeId>` row is never touched.
140047
+ */
140048
+ async function clearFixedPin(ports) {
140049
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140050
+ outcome: "already-done",
140051
+ summary: { cleared: false }
140052
+ };
140053
+ await ports.clearFixedPin();
140054
+ return {
140055
+ outcome: "done",
140056
+ summary: { cleared: true }
140057
+ };
140058
+ }
140059
+ async function planDropGlobalKnobRows(addonId, ports) {
140060
+ const stored = await ports.readStored([
140061
+ "bridgeName",
140062
+ "fixedPin",
140063
+ "interfaceName",
140064
+ nodeKeyOf("interfaceName")
140065
+ ]);
140066
+ const present = [
140067
+ "bridgeName",
140068
+ "fixedPin",
140069
+ "interfaceName"
140070
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140071
+ if (present.length === 0) return { edits: [] };
140072
+ const rowId = (key) => `${addonId}.${key}`;
140073
+ return { edits: [{
140074
+ op: "deleteKeys",
140075
+ scope: ADDON_SETTINGS_TABLE,
140076
+ keys: present.map(rowId),
140077
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140078
+ addonId,
140079
+ key,
140080
+ value: stored[key]
140081
+ }])))
140082
+ }] };
140083
+ }
140084
+ //#endregion
139827
140085
  //#region src/migrations/index.ts
139828
140086
  var EXPORT_HAP_ID = "export-hap";
139829
140087
  var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139830
140088
  var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139831
140089
  var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139832
140090
  var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140091
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140092
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140093
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
139833
140094
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
139834
140095
  var ADDON_MIGRATIONS = [
139835
140096
  {
@@ -139898,7 +140159,7 @@ var ADDON_MIGRATIONS = [
139898
140159
  },
139899
140160
  {
139900
140161
  meta: {
139901
- id: "export-hap/2026-11-04-drop-exposure-keys",
140162
+ id: DROP_EXPOSURE_KEYS_ID,
139902
140163
  owner: EXPORT_HAP_ID,
139903
140164
  level: "addon-state",
139904
140165
  seq: 5,
@@ -139911,6 +140172,58 @@ var ADDON_MIGRATIONS = [
139911
140172
  fixtureMark: "the bridge name the migration does not know"
139912
140173
  },
139913
140174
  plan: planDropExposureKeys
140175
+ },
140176
+ {
140177
+ meta: {
140178
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140179
+ owner: EXPORT_HAP_ID,
140180
+ level: "addon-state",
140181
+ seq: 6,
140182
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140183
+ store: "settings",
140184
+ scope: "cluster",
140185
+ onFailure: "block-owner",
140186
+ bodyKind: "procedure",
140187
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140188
+ fixtureMark: "the bridge name the migration does not know"
140189
+ },
140190
+ procedure: moveBridgeNameToInstance
140191
+ },
140192
+ {
140193
+ meta: {
140194
+ id: DROP_GLOBAL_KNOBS_ID,
140195
+ owner: EXPORT_HAP_ID,
140196
+ level: "addon-state",
140197
+ seq: 7,
140198
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140199
+ store: "settings",
140200
+ scope: "cluster",
140201
+ onFailure: "tolerate",
140202
+ bodyKind: "procedure",
140203
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140204
+ fixtureMark: "the bridge name the migration does not know"
140205
+ },
140206
+ procedure: clearFixedPin
140207
+ },
140208
+ {
140209
+ meta: {
140210
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140211
+ owner: EXPORT_HAP_ID,
140212
+ level: "addon-state",
140213
+ seq: 8,
140214
+ dependsOn: [
140215
+ BRIDGE_NAME_TO_INSTANCE_ID,
140216
+ DROP_GLOBAL_KNOBS_ID,
140217
+ INTERFACE_NAME_PER_NODE_ID
140218
+ ],
140219
+ store: "settings",
140220
+ scope: "cluster",
140221
+ onFailure: "tolerate",
140222
+ bodyKind: "plan",
140223
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140224
+ fixtureMark: "the bridge name the migration does not know"
140225
+ },
140226
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
139914
140227
  }
139915
140228
  ];
139916
140229
  //#endregion
@@ -158005,81 +158318,6 @@ function errMsg$3(err) {
158005
158318
  return err instanceof Error ? err.message : String(err);
158006
158319
  }
158007
158320
  //#endregion
158008
- //#region src/mappers/kind.ts
158009
- /**
158010
- * Which orchestrator a device gets, which device types the picker offers, and
158011
- * what a device's HomeKit accessory is called on the wire.
158012
- *
158013
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
158014
- * import the uuid convention without importing the registry that imports them.
158015
- */
158016
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
158017
- /**
158018
- * The device types the Export picker offers, and the answer to the cap's
158019
- * `listSupportedDeviceKinds`.
158020
- *
158021
- * A UI FILTER, nothing more. Whether a device actually exports anything is
158022
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
158023
- * doctrine the HA exporter writes down, and the thing that confined the
158024
- * previous exporter to cameras when it was ignored.
158025
- *
158026
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
158027
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
158028
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
158029
- * absent — each needs a service whose semantics the table cannot yet honour,
158030
- * and offering the tab before the mapping exists is how an operator gets an
158031
- * accessory that pairs and does nothing.
158032
- *
158033
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
158034
- * (`builders/generic/security-system.ts`), and the two things the table could
158035
- * not previously honour are now honoured explicitly: HomeKit is only ever
158036
- * offered the arm modes the panel accepts, and a panel that requires a PIN
158037
- * refuses the write out loud instead of pretending to arm.
158038
- */
158039
- var HAP_EXPORTABLE_DEVICE_TYPES = [
158040
- DeviceType.Camera,
158041
- DeviceType.Light,
158042
- DeviceType.Switch,
158043
- DeviceType.Siren,
158044
- DeviceType.Sensor,
158045
- DeviceType.Lock,
158046
- DeviceType.Presence,
158047
- DeviceType.AlarmPanel,
158048
- DeviceType.Generic
158049
- ];
158050
- /**
158051
- * Resolve the orchestrator for a device from its TYPE.
158052
- *
158053
- * `null` means "no Export tab": the picker must not offer a type no
158054
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
158055
- * to `camera` — that is what every entry persisted before this function existed
158056
- * carries, and a transient API failure must never re-shape an exposed camera.
158057
- */
158058
- function pickMapperKind(deviceType) {
158059
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
158060
- if (deviceType === DeviceType.Camera) return "camera";
158061
- const withheld = applianceExport("homekit", deviceType);
158062
- if (withheld !== null && !withheld.exported) return null;
158063
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
158064
- }
158065
- /**
158066
- * The deterministic HAP accessory UUID for a device.
158067
- *
158068
- * One function, because three call sites depend on the answer agreeing: the
158069
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
158070
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
158071
- * and the export sync state that records it.
158072
- *
158073
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
158074
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
158075
- * would make every paired camera a stranger. Generic devices get their own
158076
- * namespace so a switch and a camera that happen to share a device id are not
158077
- * the same HomeKit accessory.
158078
- */
158079
- function accessoryUuidFor(kind, deviceId) {
158080
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
158081
- }
158082
- //#endregion
158083
158321
  //#region src/multi-tier/rtp-streaming-control.ts
158084
158322
  /**
158085
158323
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -158882,7 +159120,7 @@ async function buildCameraAccessory(input) {
158882
159120
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
158883
159121
  const isDoorbell = capNames.has("doorbell");
158884
159122
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
158885
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159123
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
158886
159124
  accessory.category = category;
158887
159125
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
158888
159126
  const bctx = {
@@ -159017,7 +159255,7 @@ async function buildGenericAccessory(input) {
159017
159255
  const rows = rowsForCaps(capNames);
159018
159256
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
159019
159257
  const deviceType = await resolveDeviceType(proxy);
159020
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159258
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
159021
159259
  accessory.category = accessoryCategoryFor(deviceType);
159022
159260
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
159023
159261
  const bctx = {
@@ -159250,8 +159488,6 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159250
159488
  }
159251
159489
  ];
159252
159490
  var DEFAULT_CONFIG = {
159253
- bridgeName: "CamStack Bridge",
159254
- fixedPin: "",
159255
159491
  interfaceName: "",
159256
159492
  clipRetentionDays: 14,
159257
159493
  exportSyncState: {}
@@ -159270,10 +159506,6 @@ var BANNED_PINCODES = new Set([
159270
159506
  "123-45-678",
159271
159507
  "876-54-321"
159272
159508
  ]);
159273
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
159274
- function isValidPincode(pin) {
159275
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
159276
- }
159277
159509
  function generateUsername() {
159278
159510
  const bytes = (0, node_crypto.randomBytes)(6);
159279
159511
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -159288,33 +159520,23 @@ function generatePincode() {
159288
159520
  }
159289
159521
  throw new Error("export-hap: failed to generate a non-trivial pincode");
159290
159522
  }
159523
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
159291
159524
  function buildBridgeUuid(bridgeName) {
159292
159525
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
159293
159526
  }
159294
159527
  var ExportHapAddon = class extends BaseAddon {
159295
159528
  /**
159296
- * The old `identity.pincode` secret: declared only so the identity migration can release its
159297
- * keychain entry when it clears the old setting. The identity itself is a record now.
159529
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159530
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159298
159531
  */
159299
- secretStatePaths = ["identity.pincode"];
159300
- exposed = /* @__PURE__ */ new Map();
159301
- /** The exported actions — switches beside the devices (D968). */
159302
- actionExports = null;
159532
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159533
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159534
+ bridges = /* @__PURE__ */ new Map();
159535
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159536
+ lifecycle = Promise.resolve();
159303
159537
  lastError;
159304
159538
  /** The HomeKit instances (D985): one record per bridge identity. */
159305
159539
  instances = null;
159306
- /**
159307
- * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159308
- * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159309
- * boot and written through on every change; this addon is the record's only writer.
159310
- */
159311
- exposure = {
159312
- name: HAP_EXPOSURE_NAME,
159313
- devices: [],
159314
- actions: []
159315
- };
159316
- /** Shared HAP setup code applied to every published accessory. */
159317
- pincode = "";
159318
159540
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
159319
159541
  bind;
159320
159542
  /**
@@ -159358,12 +159580,6 @@ var ExportHapAddon = class extends BaseAddon {
159358
159580
  hksvBuilds = new HksvBuildOutcomes();
159359
159581
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
159360
159582
  hksvClipPlanes = null;
159361
- /**
159362
- * THE bridge. Lazily created and published the first time a non-camera
159363
- * accessory needs it; never torn down while the addon runs, because an
159364
- * unpublish would drop a pairing the operator already entered a code for.
159365
- */
159366
- bridgeHost = null;
159367
159583
  constructor() {
159368
159584
  super({ ...DEFAULT_CONFIG });
159369
159585
  }
@@ -159377,31 +159593,24 @@ var ExportHapAddon = class extends BaseAddon {
159377
159593
  this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159378
159594
  description: {
159379
159595
  role: "services",
159380
- instanceMode: "single",
159596
+ instanceMode: "multiple",
159381
159597
  kind: "bridge",
159382
159598
  canTest: false
159383
159599
  },
159384
- formSchema: () => this.schema({ sections: [] }),
159600
+ formSchema: (id) => this.bridgeForm(id),
159385
159601
  initialBody: (name) => ({
159386
159602
  name,
159387
159603
  username: generateUsername(),
159388
159604
  uuid: buildBridgeUuid(name),
159389
159605
  pincode: generatePincode()
159390
159606
  }),
159391
- configured: (body) => body.username !== "" && body.pincode !== ""
159607
+ mintId: () => `hap-${(0, node_crypto.randomUUID)().slice(0, 8)}`,
159608
+ configured: (body) => body.username !== "" && body.pincode !== "",
159609
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159392
159610
  });
159393
159611
  await this.migrateSettings();
159394
- const identity = await this.ensureIdentity();
159395
- await this.loadExposure();
159396
- this.pincode = identity.pincode;
159612
+ await this.ensureDefaultBridge();
159397
159613
  this.bind = this.config.interfaceName || void 0;
159398
- this.bridgeHost = new BridgeHost({
159399
- displayName: this.config.bridgeName,
159400
- uuid: identity.uuid,
159401
- pincode: identity.pincode,
159402
- bind: this.bind,
159403
- logger: this.ctx.logger
159404
- });
159405
159614
  try {
159406
159615
  await initHapStorage(node_path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
159407
159616
  } catch (err) {
@@ -159415,7 +159624,7 @@ var ExportHapAddon = class extends BaseAddon {
159415
159624
  this.hksvClipStore = new HksvClipStore({
159416
159625
  logger: this.ctx.logger.child("hksv-clips"),
159417
159626
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
159418
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159627
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159419
159628
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
159420
159629
  resolveFfmpeg: this.pinnedFfmpeg,
159421
159630
  spawnFn: node_child_process.spawn,
@@ -159428,161 +159637,323 @@ var ExportHapAddon = class extends BaseAddon {
159428
159637
  }) })
159429
159638
  });
159430
159639
  await this.serveHksvClipPlanes();
159640
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159641
+ for (const row of ordered) try {
159642
+ await this.startInstance(row.id);
159643
+ } catch (err) {
159644
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159645
+ instanceId: row.id,
159646
+ error: errMsg(err)
159647
+ } });
159648
+ }
159649
+ this.ctx.addDisposer(async () => {
159650
+ await this.enqueue(async () => {
159651
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159652
+ });
159653
+ });
159654
+ this.subscribeDeviceProvisionedForReconcile();
159655
+ this.subscribeDeviceReadyForReconcile();
159656
+ this.subscribeStorageLocationsForClips();
159657
+ const provider = this.buildExportProvider();
159658
+ const clipsProvider = createHksvVideoclipsProvider({
159659
+ logger: this.ctx.logger.child("hksv-clips"),
159660
+ addonId: EXPORT_HAP_ADDON_ID,
159661
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159662
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159663
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159664
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159665
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159666
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159667
+ });
159668
+ return {
159669
+ providers: [
159670
+ {
159671
+ capability: deviceExportCapability,
159672
+ provider
159673
+ },
159674
+ {
159675
+ capability: videoclipsCapability,
159676
+ provider: clipsProvider
159677
+ },
159678
+ {
159679
+ capability: integrationInstancesCapability,
159680
+ provider: this.requireInstances().toProvider()
159681
+ }
159682
+ ],
159683
+ customActions: exportHapActions,
159684
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159685
+ };
159686
+ }
159687
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159688
+ enqueue(job) {
159689
+ const run = this.lifecycle.then(job);
159690
+ this.lifecycle = run.then(() => void 0, () => void 0);
159691
+ return run;
159692
+ }
159693
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159694
+ instanceForDevice(deviceId) {
159695
+ const key = String(deviceId);
159696
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159697
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159698
+ }
159699
+ requireBridge(instanceId) {
159700
+ const inst = this.bridges.get(instanceId);
159701
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159702
+ return inst;
159703
+ }
159704
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159705
+ async startInstance(id) {
159706
+ await this.stopInstance(id);
159707
+ const resolved = await this.requireInstances().readResolved(id);
159708
+ if (resolved === null || !resolved.enabled) return;
159709
+ if (resolved.secrets === "unavailable") {
159710
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159711
+ return;
159712
+ }
159713
+ const identity = identityOfBody(resolved.body);
159714
+ const exposure = await this.loadExposure(id);
159715
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159716
+ displayName: resolved.body.name,
159717
+ uuid: identity.uuid,
159718
+ pincode: identity.pincode,
159719
+ bind: this.bind,
159720
+ logger: this.ctx.logger
159721
+ }), exposure);
159722
+ this.bridges.set(id, inst);
159723
+ this.warnOnDuplicateName(inst);
159431
159724
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
159432
- const cleaned = this.exposure.devices.filter((entry) => {
159725
+ const cleaned = inst.exposure.devices.filter((entry) => {
159433
159726
  if (validKinds.has(entry.mapperKind)) return true;
159434
159727
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
159435
159728
  return false;
159436
159729
  });
159437
- if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
159730
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
159438
159731
  for (const entry of cleaned) {
159439
159732
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
159440
159733
  try {
159441
- await this.attachMapper(entry);
159734
+ await this.attachMapper(inst, entry);
159442
159735
  const numericId = Number.parseInt(entry.deviceId, 10);
159443
159736
  if (Number.isFinite(numericId)) {
159444
- const fp = await this.computeExportFingerprint(numericId);
159445
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159737
+ const fp = await this.computeExportFingerprint(inst, numericId);
159738
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159446
159739
  }
159447
159740
  } catch (err) {
159448
159741
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
159449
159742
  }
159450
159743
  }
159451
- this.actionExports = new ActionExports({
159744
+ inst.actionExports = new ActionExports({
159452
159745
  api: this.ctx.api,
159453
159746
  logger: this.ctx.logger,
159747
+ instanceId: id,
159454
159748
  publish: async (accessory) => {
159455
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159749
+ if (await inst.bridgeHost.add(accessory)) return;
159456
159750
  await publishStandalone(accessory, {
159457
- pincode: this.pincode,
159751
+ pincode: inst.pincode,
159458
159752
  port: 0,
159459
159753
  bind: this.bind,
159460
159754
  logger: this.ctx.logger
159461
159755
  });
159462
159756
  },
159463
159757
  unpublish: async (accessory) => {
159464
- if (this.bridgeHost?.holds(accessory) === true) {
159465
- this.bridgeHost.remove(accessory);
159758
+ if (inst.bridgeHost.holds(accessory)) {
159759
+ inst.bridgeHost.remove(accessory);
159466
159760
  return;
159467
159761
  }
159468
159762
  await unpublishAccessory(accessory, this.ctx.logger);
159469
159763
  },
159470
- persist: (entries) => this.setExposedActions(entries)
159471
- }, this.exposure.actions);
159472
- await this.actionExports.attachAll();
159473
- await this.actionExports.reconcile();
159474
- this.ctx.addDisposer(async () => {
159475
- await this.actionExports?.dispose();
159476
- await this.detachAll();
159477
- await this.bridgeHost?.dispose();
159764
+ persist: (entries) => this.setExposedActions(inst, entries)
159765
+ }, inst.exposure.actions);
159766
+ await inst.actionExports.attachAll();
159767
+ await inst.actionExports.reconcile();
159768
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159769
+ instanceId: id,
159770
+ name: inst.name,
159771
+ devices: inst.exposed.size
159772
+ } });
159773
+ }
159774
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159775
+ async stopInstance(id) {
159776
+ const inst = this.bridges.get(id);
159777
+ if (inst === void 0) return;
159778
+ this.bridges.delete(id);
159779
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159780
+ inst.pendingRebuildTimers.clear();
159781
+ await inst.actionExports?.dispose();
159782
+ await this.detachAll(inst);
159783
+ await inst.bridgeHost.dispose();
159784
+ }
159785
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159786
+ async applyChange(id, change) {
159787
+ if (change === "deleted") {
159788
+ await this.removeInstance(id);
159789
+ return;
159790
+ }
159791
+ const resolved = await this.requireInstances().readResolved(id);
159792
+ if (resolved === null || !resolved.enabled) {
159793
+ await this.stopInstance(id);
159794
+ return;
159795
+ }
159796
+ const running = this.bridges.get(id);
159797
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159798
+ const next = identityOfBody(resolved.body);
159799
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159800
+ }
159801
+ await this.startInstance(id);
159802
+ }
159803
+ /**
159804
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159805
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159806
+ */
159807
+ async removeInstance(id) {
159808
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159809
+ await this.stopInstance(id);
159810
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159811
+ await this.exposureHandle().delete(id);
159812
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159813
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159814
+ }
159815
+ /**
159816
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159817
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159818
+ * devices stay.
159819
+ */
159820
+ regenerateBridge(instanceId) {
159821
+ return this.enqueue(async () => {
159822
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159823
+ await this.stopInstance(instanceId);
159824
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159825
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159826
+ await this.startInstance(instanceId);
159827
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159828
+ instanceId,
159829
+ accessories: uuids.length
159830
+ } });
159831
+ return { regenerated: true };
159478
159832
  });
159479
- this.subscribeDeviceProvisionedForReconcile();
159480
- this.subscribeDeviceReadyForReconcile();
159481
- this.subscribeStorageLocationsForClips();
159482
- this.disposeSharedRebuildTimers();
159483
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
159484
- const provider = {
159485
- getStatus: async (input) => {
159486
- ownInstance(statusInstanceOf(input));
159487
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
159488
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159489
- const setup = this.buildSetupBlock();
159490
- return {
159491
- linkState,
159492
- exposedDeviceCount: this.exposed.size,
159493
- ...this.lastError ? { error: this.lastError } : {},
159494
- ...setup ? { setup } : {}
159495
- };
159496
- },
159497
- listInstances: async () => [{
159498
- instanceId: EXPORT_HAP_ADDON_ID,
159499
- name: "HomeKit",
159500
- enabled: true,
159833
+ }
159834
+ warnOnDuplicateName(inst) {
159835
+ const key = inst.name.trim().toLowerCase();
159836
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159837
+ if (others.length === 0) return;
159838
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159839
+ instanceId: inst.id,
159840
+ name: inst.name,
159841
+ others: others.map((b) => b.id)
159842
+ } });
159843
+ }
159844
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159845
+ bridgeForm(id) {
159846
+ const inst = id === null ? void 0 : this.bridges.get(id);
159847
+ let qr = "";
159848
+ try {
159849
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159850
+ } catch (err) {
159851
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159852
+ instanceId: id,
159853
+ error: errMsg(err)
159854
+ } });
159855
+ }
159856
+ return this.schema({ sections: [{
159857
+ id: "bridge",
159858
+ title: "HomeKit bridge",
159859
+ description: "One HomeKit bridge carries every exported device that is not a camera (switches, sensors, locks, alarm panels); each camera is published as its own accessory with the same setup code. In iOS Home tap + → Add Accessory and enter the setup code.",
159860
+ fields: [...inst === void 0 ? [] : [{
159861
+ type: "info",
159862
+ key: "setupCode",
159863
+ label: "Setup code",
159864
+ content: inst.pincode
159865
+ }, ...qr === "" ? [] : [{
159866
+ type: "qr-code",
159867
+ key: "setupQr",
159868
+ label: "Pairing QR",
159869
+ caption: "Scan with the iOS Camera app.",
159870
+ value: qr,
159871
+ size: 192
159872
+ }]], ...id === null ? [] : [{
159873
+ type: "addon-action-button",
159874
+ key: "__regenerate-bridge",
159875
+ label: "Regenerate setup code",
159876
+ description: "Creates a new setup code and unpairs every controller from this bridge: each iPhone, iPad and Apple TV must add it again. The bridge and its exported devices stay.",
159877
+ addonId: EXPORT_HAP_ADDON_ID,
159878
+ action: "regenerateBridge",
159879
+ buttonLabel: "Regenerate",
159880
+ variant: "danger",
159881
+ paramsStatic: { instanceId: id },
159882
+ confirmMessage: "Regenerate the setup code? Every controller paired with this bridge is unpaired, its pairings are cleared and the bridge is republished. You must pair each one again with the new code."
159883
+ }]]
159884
+ }] });
159885
+ }
159886
+ /** Whole-addon status of the bridges: linked when any is paired. */
159887
+ statusOf(bridges) {
159888
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
159889
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159890
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
159891
+ return {
159892
+ linkState,
159893
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
159894
+ ...this.lastError ? { error: this.lastError } : {},
159895
+ ...setup ? { setup } : {}
159896
+ };
159897
+ }
159898
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
159899
+ bridgesOf(instanceId) {
159900
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
159901
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159902
+ }
159903
+ buildExportProvider() {
159904
+ return {
159905
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
159906
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
159907
+ instanceId: row.id,
159908
+ name: row.body.name,
159909
+ enabled: row.enabled,
159501
159910
  kind: "hap-bridge"
159502
- }],
159911
+ })),
159503
159912
  listSupportedDeviceKinds: async ({ instanceId }) => {
159504
- ownInstance(instanceId);
159913
+ this.bridgesOf(instanceId);
159505
159914
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
159506
159915
  },
159507
- listExposedDevices: async ({ instanceId }) => {
159508
- ownInstance(instanceId);
159509
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159510
- const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159511
- return {
159512
- deviceId,
159513
- exposedAs: m.accessory.displayName,
159514
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159515
- };
159516
- });
159517
- },
159518
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159519
- ownInstance(instanceId);
159520
- return this.exposeDevice(deviceId, capabilities);
159521
- },
159522
- unexposeDevice: async ({ instanceId, deviceId }) => {
159523
- ownInstance(instanceId);
159524
- return this.unexposeDevice(deviceId);
159525
- },
159916
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
159917
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159918
+ return {
159919
+ deviceId,
159920
+ exposedAs: m.accessory.displayName,
159921
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159922
+ };
159923
+ })),
159924
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
159925
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
159526
159926
  listSupportedEntityKinds: async () => ["device", "action"],
159527
159927
  listExposedEntities: async ({ instanceId }) => {
159528
- ownInstance(instanceId);
159529
- await this.actionExports?.reconcile();
159530
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
159531
- entity: {
159532
- kind: "device",
159533
- deviceId
159534
- },
159535
- exposedAs: m.accessory.displayName
159536
- })), ...this.actionExports?.list() ?? []];
159928
+ const out = [];
159929
+ for (const inst of this.bridgesOf(instanceId)) {
159930
+ await inst.actionExports?.reconcile();
159931
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
159932
+ entity: {
159933
+ kind: "device",
159934
+ deviceId
159935
+ },
159936
+ exposedAs: m.accessory.displayName
159937
+ })), ...inst.actionExports?.list() ?? []);
159938
+ }
159939
+ return out;
159537
159940
  },
159538
159941
  exposeEntity: async ({ instanceId, entity }) => {
159539
- ownInstance(instanceId);
159540
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
159541
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
159942
+ const inst = this.requireBridge(instanceId);
159943
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
159944
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
159542
159945
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159543
159946
  },
159544
159947
  unexposeEntity: async ({ instanceId, entity }) => {
159545
- ownInstance(instanceId);
159546
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
159547
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
159948
+ const inst = this.requireBridge(instanceId);
159949
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
159950
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
159548
159951
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159549
159952
  },
159550
159953
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
159551
159954
  getDeviceLiveContribution: async () => null,
159552
159955
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
159553
159956
  };
159554
- const clipsProvider = createHksvVideoclipsProvider({
159555
- logger: this.ctx.logger.child("hksv-clips"),
159556
- addonId: EXPORT_HAP_ADDON_ID,
159557
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
159558
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159559
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159560
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159561
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159562
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159563
- });
159564
- return [
159565
- {
159566
- capability: deviceExportCapability,
159567
- provider
159568
- },
159569
- {
159570
- capability: videoclipsCapability,
159571
- provider: clipsProvider
159572
- },
159573
- {
159574
- capability: integrationInstancesCapability,
159575
- provider: this.requireInstances().toProvider()
159576
- }
159577
- ];
159578
- }
159579
- async onConfigChanged() {
159580
- const fixedPin = this.config.fixedPin;
159581
- if (!fixedPin || !isValidPincode(fixedPin)) return;
159582
- const handle = this.requireRecords().kind(hapBridgesKind);
159583
- const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159584
- if (row === null || row.data.pincode === fixedPin) return;
159585
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159586
159957
  }
159587
159958
  requireInstances() {
159588
159959
  if (this.instances === null) throw new Error("export-hap: instances are not initialised");
@@ -159616,13 +159987,17 @@ var ExportHapAddon = class extends BaseAddon {
159616
159987
  }
159617
159988
  return "created";
159618
159989
  },
159619
- readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
159990
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
159991
+ patchDefaultName: async (name) => {
159992
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
159993
+ },
159994
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
159620
159995
  };
159621
159996
  }
159622
- /** The identity of the default instance; see `resolveBridgeIdentity`. */
159623
- async ensureIdentity() {
159997
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
159998
+ async ensureDefaultBridge() {
159624
159999
  const handle = this.requireRecords().kind(hapBridgesKind);
159625
- const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
160000
+ const boot = await resolveDefaultBridge({
159626
160001
  readRecord: async () => {
159627
160002
  const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159628
160003
  if (resolved === null) return { kind: "absent" };
@@ -159632,9 +160007,7 @@ var ExportHapAddon = class extends BaseAddon {
159632
160007
  } : { kind: "unavailable" };
159633
160008
  },
159634
160009
  legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159635
- patchPincode: async (pincode) => {
159636
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159637
- },
160010
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
159638
160011
  putFresh: async (body) => {
159639
160012
  await handle.put({
159640
160013
  id: HAP_DEFAULT_INSTANCE_ID,
@@ -159642,14 +160015,13 @@ var ExportHapAddon = class extends BaseAddon {
159642
160015
  }, { ifRev: 0 });
159643
160016
  },
159644
160017
  mint: () => ({
159645
- name: this.config.bridgeName,
160018
+ name: DEFAULT_BRIDGE_NAME,
159646
160019
  username: generateUsername(),
159647
- uuid: buildBridgeUuid(this.config.bridgeName),
160020
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
159648
160021
  pincode: generatePincode()
159649
160022
  })
159650
160023
  });
159651
- if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159652
- return identity;
160024
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
159653
160025
  }
159654
160026
  /**
159655
160027
  * Build the generic `device-export` `setup` block surfaced via
@@ -159658,10 +160030,10 @@ var ExportHapAddon = class extends BaseAddon {
159658
160030
  * a copyable field, and a short pairing instruction. Returns `null`
159659
160031
  * until the bridge has booted and produced both values.
159660
160032
  */
159661
- buildSetupBlock() {
159662
- const setupCode = this.pincode;
160033
+ buildSetupBlock(inst) {
160034
+ const setupCode = inst.pincode;
159663
160035
  if (!setupCode) return null;
159664
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160036
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
159665
160037
  return {
159666
160038
  ...qr !== void 0 ? { qr } : {},
159667
160039
  fields: [{
@@ -159682,18 +160054,18 @@ var ExportHapAddon = class extends BaseAddon {
159682
160054
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
159683
160055
  * still said `streamPreference=auto`.
159684
160056
  */
159685
- async exposeDevice(deviceId, capabilities, settings) {
160057
+ async exposeDevice(inst, deviceId, capabilities, settings) {
159686
160058
  const numericId = Number.parseInt(deviceId, 10);
159687
160059
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159688
- if (this.exposed.has(deviceId)) {
160060
+ if (inst.exposed.has(deviceId)) {
159689
160061
  log.debug("export-hap: device already exposed — refreshing capabilities");
159690
- await this.detachMapper(deviceId);
160062
+ await this.detachMapper(inst, deviceId);
159691
160063
  }
159692
160064
  const summary = await this.fetchDeviceSummary(numericId);
159693
160065
  const mapperKind = pickMapperKind(summary?.type);
159694
160066
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
159695
160067
  const displayName = summary?.name ?? `Device ${deviceId}`;
159696
- const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
160068
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159697
160069
  const rebuilt = {
159698
160070
  deviceId,
159699
160071
  displayName,
@@ -159705,37 +160077,38 @@ var ExportHapAddon = class extends BaseAddon {
159705
160077
  ...rebuilt,
159706
160078
  settings
159707
160079
  }, previous, ["settings", "capabilities"]);
159708
- const attached = await this.attachMapper(baseEntry);
160080
+ const attached = await this.attachMapper(inst, baseEntry);
159709
160081
  const finalEntry = {
159710
160082
  ...baseEntry,
159711
160083
  childAccessoryUuids: attached.childAccessoryUuids
159712
160084
  };
159713
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
160085
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
159714
160086
  next.push(finalEntry);
159715
- await this.setExposedDevices(next);
160087
+ await this.setExposedDevices(inst, next);
159716
160088
  if (Number.isFinite(numericId)) {
159717
- const fp = await this.computeExportFingerprint(numericId);
159718
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160089
+ const fp = await this.computeExportFingerprint(inst, numericId);
160090
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159719
160091
  }
159720
160092
  log.info("export-hap: exposed device", { meta: {
160093
+ instanceId: inst.id,
159721
160094
  displayName,
159722
160095
  mapperKind,
159723
160096
  childCount: attached.childAccessoryUuids.length
159724
160097
  } });
159725
160098
  }
159726
- async unexposeDevice(deviceId, options = {}) {
160099
+ async unexposeDevice(inst, deviceId, options = {}) {
159727
160100
  const numericId = Number.parseInt(deviceId, 10);
159728
160101
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159729
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
159730
- await this.detachMapper(deviceId);
159731
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159732
- if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
159733
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
159734
- await this.forgetFingerprint(numericId);
160102
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160103
+ await this.detachMapper(inst, deviceId);
160104
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160105
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160106
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160107
+ await this.forgetFingerprint(inst, numericId);
159735
160108
  this.hksvBuilds.forget(numericId);
159736
- log.info("export-hap: unexposed device");
160109
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
159737
160110
  }
159738
- async attachMapper(entry) {
160111
+ async attachMapper(inst, entry) {
159739
160112
  const factory = getMapperFactory(entry.mapperKind);
159740
160113
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
159741
160114
  const mapper = await factory({
@@ -159743,6 +160116,7 @@ var ExportHapAddon = class extends BaseAddon {
159743
160116
  deviceId: entry.deviceId,
159744
160117
  displayName: entry.displayName,
159745
160118
  options: {
160119
+ instanceId: inst.id,
159746
160120
  decodeMemos: this.decodeMemos,
159747
160121
  resolveFfmpeg: this.pinnedFfmpeg,
159748
160122
  hksvClipStore: this.hksvClipStore,
@@ -159762,29 +160136,29 @@ var ExportHapAddon = class extends BaseAddon {
159762
160136
  useBridge: entry.settings?.useBridge
159763
160137
  });
159764
160138
  for (const accessory of mapper.accessories) {
159765
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160139
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
159766
160140
  await publishStandalone(accessory, {
159767
- pincode: this.pincode,
160141
+ pincode: inst.pincode,
159768
160142
  port: 0,
159769
160143
  bind: this.bind,
159770
160144
  logger: this.ctx.logger
159771
160145
  });
159772
160146
  }
159773
- this.exposed.set(entry.deviceId, mapper);
160147
+ inst.exposed.set(entry.deviceId, mapper);
159774
160148
  return { childAccessoryUuids: [] };
159775
160149
  }
159776
- async detachMapper(deviceId) {
159777
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160150
+ async detachMapper(inst, deviceId) {
160151
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
159778
160152
  if (pendingTimer) {
159779
160153
  clearTimeout(pendingTimer);
159780
- this.pendingRebuildTimers.delete(deviceId);
160154
+ inst.pendingRebuildTimers.delete(deviceId);
159781
160155
  }
159782
- const mapper = this.exposed.get(deviceId);
160156
+ const mapper = inst.exposed.get(deviceId);
159783
160157
  if (!mapper) return;
159784
- this.exposed.delete(deviceId);
160158
+ inst.exposed.delete(deviceId);
159785
160159
  for (const accessory of mapper.accessories) {
159786
- if (this.bridgeHost?.holds(accessory) === true) {
159787
- this.bridgeHost.remove(accessory);
160160
+ if (inst.bridgeHost.holds(accessory)) {
160161
+ inst.bridgeHost.remove(accessory);
159788
160162
  continue;
159789
160163
  }
159790
160164
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -159793,21 +160167,22 @@ var ExportHapAddon = class extends BaseAddon {
159793
160167
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
159794
160168
  });
159795
160169
  }
159796
- requireActionExports() {
159797
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
159798
- return this.actionExports;
160170
+ requireActionExports(inst) {
160171
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160172
+ return inst.actionExports;
159799
160173
  }
159800
- async detachAll() {
159801
- const ids = Array.from(this.exposed.keys());
159802
- for (const id of ids) await this.detachMapper(id);
160174
+ async detachAll(inst) {
160175
+ const ids = Array.from(inst.exposed.keys());
160176
+ for (const id of ids) await this.detachMapper(inst, id);
159803
160177
  }
159804
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
159805
- * on detach so stale timers can't republish a removed accessory. */
159806
- pendingRebuildTimers = /* @__PURE__ */ new Map();
159807
160178
  /** Deterministic HAP accessory UUID for a device — the same one the
159808
160179
  * orchestrator built it with (`mappers/kind.ts`). */
159809
- hapAccessoryUuid(deviceId) {
159810
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160180
+ hapAccessoryUuid(inst, deviceId) {
160181
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160182
+ }
160183
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160184
+ syncStateOf(inst) {
160185
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
159811
160186
  }
159812
160187
  /**
159813
160188
  * Export fingerprint of a device from its PERSISTED features + type
@@ -159825,7 +160200,7 @@ var ExportHapAddon = class extends BaseAddon {
159825
160200
  * A brand-new un-probed device with no persisted entry falls back to its
159826
160201
  * fresh fingerprint (publishes once, acceptable).
159827
160202
  */
159828
- async computeExportFingerprint(deviceId) {
160203
+ async computeExportFingerprint(inst, deviceId) {
159829
160204
  try {
159830
160205
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
159831
160206
  if (!device) return null;
@@ -159834,10 +160209,10 @@ var ExportHapAddon = class extends BaseAddon {
159834
160209
  deviceType: device.type,
159835
160210
  features: device.features
159836
160211
  });
159837
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160212
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
159838
160213
  const withToken = withRecordabilityToken({
159839
160214
  base: fresh,
159840
- token: await this.readRecordabilityToken(deviceId, device.type),
160215
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
159841
160216
  persisted
159842
160217
  });
159843
160218
  return resolveExportFingerprint({
@@ -159857,12 +160232,12 @@ var ExportHapAddon = class extends BaseAddon {
159857
160232
  * republish every non-camera accessory once for nothing) and for a camera
159858
160233
  * whose profiles could not be read right now.
159859
160234
  */
159860
- async readRecordabilityToken(deviceId, type) {
160235
+ async readRecordabilityToken(inst, deviceId, type) {
159861
160236
  if (pickMapperKind(type) !== "camera") return null;
159862
160237
  try {
159863
160238
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
159864
160239
  return recordabilityTokenFor({
159865
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160240
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
159866
160241
  entries: entries ?? null
159867
160242
  });
159868
160243
  } catch {
@@ -159871,20 +160246,20 @@ var ExportHapAddon = class extends BaseAddon {
159871
160246
  }
159872
160247
  /** Persist a device's current export fingerprint into `exportSyncState`
159873
160248
  * (best-effort; called after a successful attach). */
159874
- async persistFingerprint(deviceId, fingerprint) {
159875
- const state = syncStateFromJson(this.config.exportSyncState);
160249
+ async persistFingerprint(inst, deviceId, fingerprint) {
160250
+ const state = this.syncStateOf(inst);
159876
160251
  state.set(deviceId, {
159877
160252
  fingerprint,
159878
- externalIds: [this.hapAccessoryUuid(deviceId)]
160253
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
159879
160254
  });
159880
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160255
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159881
160256
  }
159882
160257
  /** Drop a device's `exportSyncState` entry (on unexpose). */
159883
- async forgetFingerprint(deviceId) {
159884
- const state = syncStateFromJson(this.config.exportSyncState);
160258
+ async forgetFingerprint(inst, deviceId) {
160259
+ const state = this.syncStateOf(inst);
159885
160260
  if (!state.has(deviceId)) return;
159886
160261
  state.delete(deviceId);
159887
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160262
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159888
160263
  }
159889
160264
  /**
159890
160265
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -159915,34 +160290,23 @@ var ExportHapAddon = class extends BaseAddon {
159915
160290
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
159916
160291
  if (deviceIdNumeric === null) return;
159917
160292
  const deviceId = String(deviceIdNumeric);
159918
- if (!this.findEntry(deviceIdNumeric)) return;
159919
- const existing = this.pendingRebuildTimers.get(deviceId);
159920
- if (existing) clearTimeout(existing);
159921
- const timer = setTimeout(() => {
159922
- this.pendingRebuildTimers.delete(deviceId);
159923
- this.reconcileDevice(deviceId);
159924
- }, 500);
159925
- if (typeof timer.unref === "function") timer.unref();
159926
- this.pendingRebuildTimers.set(deviceId, timer);
160293
+ for (const inst of this.bridges.values()) {
160294
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160295
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160296
+ if (existing) clearTimeout(existing);
160297
+ const timer = setTimeout(() => {
160298
+ inst.pendingRebuildTimers.delete(deviceId);
160299
+ this.reconcileDevice(inst, deviceId);
160300
+ }, 500);
160301
+ if (typeof timer.unref === "function") timer.unref();
160302
+ inst.pendingRebuildTimers.set(deviceId, timer);
160303
+ }
159927
160304
  });
159928
160305
  this.ctx.addDisposer(async () => {
159929
160306
  unsubscribe();
159930
160307
  });
159931
160308
  }
159932
160309
  /**
159933
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
159934
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
159935
- * per-device timers into `pendingRebuildTimers` but never clear the map on
159936
- * their own teardown — that shared resource is cleared here, exactly once, on
159937
- * shutdown.
159938
- */
159939
- disposeSharedRebuildTimers() {
159940
- this.ctx.addDisposer(async () => {
159941
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
159942
- this.pendingRebuildTimers.clear();
159943
- });
159944
- }
159945
- /**
159946
160310
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
159947
160311
  * its persisted export shape changes. `DeviceProvisioned` is gated by
159948
160312
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -159972,22 +160336,22 @@ var ExportHapAddon = class extends BaseAddon {
159972
160336
  * Errors are logged and swallowed — a failed reconcile leaves the prior
159973
160337
  * accessory up, which is strictly better than removing it.
159974
160338
  */
159975
- async reconcileDevice(deviceId) {
160339
+ async reconcileDevice(inst, deviceId) {
159976
160340
  const numericId = Number.parseInt(deviceId, 10);
159977
160341
  if (!Number.isFinite(numericId)) return;
159978
- const entry = this.findEntry(numericId);
160342
+ const entry = inst.findEntry(numericId);
159979
160343
  if (!entry) return;
159980
160344
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159981
- const current = await this.computeExportFingerprint(numericId);
160345
+ const current = await this.computeExportFingerprint(inst, numericId);
159982
160346
  if (current === null) {
159983
160347
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
159984
160348
  return;
159985
160349
  }
159986
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160350
+ const last = this.syncStateOf(inst).get(numericId);
159987
160351
  if (last?.fingerprint === current) {
159988
- if (!this.exposed.has(deviceId)) try {
159989
- await this.attachMapper(entry);
159990
- await this.persistFingerprint(numericId, current);
160352
+ if (!inst.exposed.has(deviceId)) try {
160353
+ await this.attachMapper(inst, entry);
160354
+ await this.persistFingerprint(inst, numericId, current);
159991
160355
  } catch (err) {
159992
160356
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
159993
160357
  }
@@ -159999,9 +160363,9 @@ var ExportHapAddon = class extends BaseAddon {
159999
160363
  to: current.slice(0, 12)
160000
160364
  } });
160001
160365
  try {
160002
- await this.detachMapper(deviceId);
160003
- await this.attachMapper(entry);
160004
- await this.persistFingerprint(numericId, current);
160366
+ await this.detachMapper(inst, deviceId);
160367
+ await this.attachMapper(inst, entry);
160368
+ await this.persistFingerprint(inst, numericId, current);
160005
160369
  } catch (err) {
160006
160370
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
160007
160371
  }
@@ -160064,7 +160428,7 @@ var ExportHapAddon = class extends BaseAddon {
160064
160428
  return null;
160065
160429
  }
160066
160430
  }
160067
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160431
+ /** The one declaration of the bind-interface field: a fact of one node. */
160068
160432
  interfaceNameField() {
160069
160433
  return this.field({
160070
160434
  type: "text",
@@ -160084,10 +160448,26 @@ var ExportHapAddon = class extends BaseAddon {
160084
160448
  fields: [this.interfaceNameField()]
160085
160449
  }] }) : null;
160086
160450
  }
160451
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160452
+ async deviceDefaultsSchema(cap) {
160453
+ return cap === "device-export" ? this.schema({ sections: [{
160454
+ id: "export-hap-defaults",
160455
+ title: "HomeKit Export",
160456
+ fields: [this.field({
160457
+ type: "number",
160458
+ key: "clipRetentionDays",
160459
+ label: "Keep HomeKit clips for (days)",
160460
+ description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
160461
+ default: DEFAULT_CONFIG.clipRetentionDays,
160462
+ placement: { tab: "advanced" }
160463
+ })]
160464
+ }] }) : null;
160465
+ }
160087
160466
  /**
160088
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
160089
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
160090
- * value the migration wrote.
160467
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160468
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160469
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160470
+ * config when anything landed, so this boot binds the value the migration wrote.
160091
160471
  */
160092
160472
  async migrateSettings() {
160093
160473
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
@@ -160097,47 +160477,24 @@ var ExportHapAddon = class extends BaseAddon {
160097
160477
  ...this.exposureMigrationPorts()
160098
160478
  }))).applied.length > 0) await this.resolveConfig();
160099
160479
  }
160480
+ /**
160481
+ * Only the declaration `perNodeKeys()` derives the node-scoped keys from: `interfaceName` is a
160482
+ * fact of one node, and the settings machinery reads a per-node key through this schema. The
160483
+ * editable surfaces are the node form, the device defaults and each bridge's own form.
160484
+ */
160100
160485
  globalSettingsSchema() {
160101
160486
  return this.schema({ sections: [{
160102
160487
  id: "export-hap",
160103
160488
  title: "HomeKit Export",
160104
- description: "Publishes each exposed device as its own HomeKit accessory, sharing one setup code. Mark a device \"Expose to HomeKit\" on its settings page, then add it in the iOS Home app (+ → Add Accessory) and enter the setup code shown there.",
160105
- columns: 1,
160106
- fields: [
160107
- this.field({
160108
- type: "text",
160109
- key: "bridgeName",
160110
- label: "Installation name",
160111
- description: "The name of the shared bridge that carries every exposed device that is not a camera (switches, sensors, locks, alarm panels) — what iOS Home lists under Add Accessory. Cameras are never bridged: each one is published as its own accessory under its device name. Set it before you add the bridge in iOS Home.",
160112
- default: DEFAULT_CONFIG.bridgeName,
160113
- requiresRestart: true,
160114
- placement: { tab: "advanced" }
160115
- }),
160116
- this.field({
160117
- type: "password",
160118
- key: "fixedPin",
160119
- label: "Fixed setup code (XXX-XX-XXX)",
160120
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
160121
- default: DEFAULT_CONFIG.fixedPin,
160122
- requiresRestart: true,
160123
- placement: { tab: "advanced" }
160124
- }),
160125
- this.interfaceNameField(),
160126
- this.field({
160127
- type: "number",
160128
- key: "clipRetentionDays",
160129
- label: "Keep HomeKit clips for (days)",
160130
- description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
160131
- default: DEFAULT_CONFIG.clipRetentionDays,
160132
- placement: { tab: "advanced" }
160133
- })
160134
- ]
160489
+ fields: [this.interfaceNameField()]
160135
160490
  }] });
160136
160491
  }
160137
160492
  async buildDeviceSettingsContribution(deviceId) {
160138
160493
  const kind = await this.resolveExportKind(deviceId);
160139
160494
  if (kind === null) return null;
160140
- const entry = this.findEntry(deviceId);
160495
+ const inst = this.instanceForDevice(deviceId);
160496
+ if (inst === null) return null;
160497
+ const entry = inst.findEntry(deviceId);
160141
160498
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
160142
160499
  const enabled = entry !== null;
160143
160500
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -160147,13 +160504,13 @@ var ExportHapAddon = class extends BaseAddon {
160147
160504
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
160148
160505
  const keepClipsKey = `hap:${deviceId}:keepClips`;
160149
160506
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
160150
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160507
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
160151
160508
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
160152
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160509
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
160153
160510
  const name = entry?.displayName ?? `Device ${deviceId}`;
160154
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
160155
- const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.pincode}.`;
160156
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160511
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160512
+ const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${inst.name}” bridge, as “${name}”` : `On the “${inst.name}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${inst.name}”, then enter setup code ${inst.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${inst.pincode}.`;
160513
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
160157
160514
  let qrValue = "";
160158
160515
  if (qrSource) try {
160159
160516
  qrValue = qrSource.setupURI();
@@ -160195,7 +160552,7 @@ var ExportHapAddon = class extends BaseAddon {
160195
160552
  type: "info",
160196
160553
  key: `hap:${deviceId}:hksvRecordingStatus`,
160197
160554
  label: "HomeKit recording (Secure Video)",
160198
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160555
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160199
160556
  showWhen: {
160200
160557
  field: enabledKey,
160201
160558
  equals: true
@@ -160279,7 +160636,7 @@ var ExportHapAddon = class extends BaseAddon {
160279
160636
  type: "qr-code",
160280
160637
  key: "__hap-pair-qr",
160281
160638
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
160282
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.pincode}.`,
160639
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
160283
160640
  value: qrValue,
160284
160641
  size: 192,
160285
160642
  alt: `HomeKit pairing QR for ${name}`,
@@ -160318,8 +160675,10 @@ var ExportHapAddon = class extends BaseAddon {
160318
160675
  async applyDeviceSettingsPatch(deviceId, patch) {
160319
160676
  const deviceIdStr = String(deviceId);
160320
160677
  const log = this.ctx.logger.withTags({ deviceId });
160321
- const current = this.findEntry(deviceId);
160322
- const wasEnabled = this.exposed.has(deviceIdStr);
160678
+ const inst = this.instanceForDevice(deviceId);
160679
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160680
+ const current = inst.findEntry(deviceId);
160681
+ const wasEnabled = inst.exposed.has(deviceIdStr);
160323
160682
  const enabledKey = `hap:${deviceId}:enabled`;
160324
160683
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
160325
160684
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -160348,12 +160707,12 @@ var ExportHapAddon = class extends BaseAddon {
160348
160707
  clipRetentionDays
160349
160708
  };
160350
160709
  if (!enabledValue) {
160351
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160710
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
160352
160711
  return { success: true };
160353
160712
  }
160354
160713
  if (!wasEnabled) {
160355
- await this.exposeDevice(deviceIdStr);
160356
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160714
+ await this.exposeDevice(inst, deviceIdStr);
160715
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160357
160716
  return { success: true };
160358
160717
  }
160359
160718
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -160367,7 +160726,7 @@ var ExportHapAddon = class extends BaseAddon {
160367
160726
  mapperKind,
160368
160727
  useBridge
160369
160728
  });
160370
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160729
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160371
160730
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
160372
160731
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
160373
160732
  streamPreference: {
@@ -160384,8 +160743,8 @@ var ExportHapAddon = class extends BaseAddon {
160384
160743
  }
160385
160744
  } });
160386
160745
  try {
160387
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
160388
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160746
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160747
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
160389
160748
  } catch (err) {
160390
160749
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
160391
160750
  }
@@ -160447,35 +160806,38 @@ var ExportHapAddon = class extends BaseAddon {
160447
160806
  exposureHandle() {
160448
160807
  return this.requireRecords().kind(hapBridgeExportsKind);
160449
160808
  }
160450
- /** Load the default instance's exposure record; create it empty when none exists. */
160451
- async loadExposure() {
160809
+ /** Load a bridge's exposure record; create it empty when none exists. */
160810
+ async loadExposure(id) {
160452
160811
  const handle = this.exposureHandle();
160453
- const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160454
- if (row !== null) {
160455
- this.exposure = row.data;
160456
- return;
160457
- }
160812
+ const row = await handle.get(id);
160813
+ if (row !== null) return row.data;
160814
+ const empty = {
160815
+ name: HAP_EXPOSURE_NAME,
160816
+ devices: [],
160817
+ actions: []
160818
+ };
160458
160819
  await handle.put({
160459
- id: HAP_DEFAULT_INSTANCE_ID,
160460
- data: this.exposure
160820
+ id,
160821
+ data: empty
160461
160822
  }, { ifRev: 0 });
160823
+ return empty;
160462
160824
  }
160463
- async writeExposure(next) {
160825
+ async writeExposure(inst, next) {
160464
160826
  await this.exposureHandle().put({
160465
- id: HAP_DEFAULT_INSTANCE_ID,
160827
+ id: inst.id,
160466
160828
  data: next
160467
160829
  });
160468
- this.exposure = next;
160830
+ inst.exposure = next;
160469
160831
  }
160470
- setExposedDevices(devices) {
160471
- return this.writeExposure({
160472
- ...this.exposure,
160832
+ setExposedDevices(inst, devices) {
160833
+ return this.writeExposure(inst, {
160834
+ ...inst.exposure,
160473
160835
  devices
160474
160836
  });
160475
160837
  }
160476
- setExposedActions(actions) {
160477
- return this.writeExposure({
160478
- ...this.exposure,
160838
+ setExposedActions(inst, actions) {
160839
+ return this.writeExposure(inst, {
160840
+ ...inst.exposure,
160479
160841
  actions
160480
160842
  });
160481
160843
  }
@@ -160499,16 +160861,12 @@ var ExportHapAddon = class extends BaseAddon {
160499
160861
  readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160500
160862
  };
160501
160863
  }
160502
- findEntry(deviceId) {
160503
- const id = String(deviceId);
160504
- return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
160505
- }
160506
- async updateEntrySettings(deviceIdStr, settings) {
160507
- const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160864
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160865
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160508
160866
  ...e,
160509
160867
  settings
160510
160868
  } : e);
160511
- await this.setExposedDevices(next);
160869
+ await this.setExposedDevices(inst, next);
160512
160870
  }
160513
160871
  };
160514
160872
  function errMsg(err) {
@@ -160523,6 +160881,7 @@ exports.default = ExportHapAddon;
160523
160881
  exports.__toCommonJS = __toCommonJS;
160524
160882
  exports.deriveUsername = deriveUsername;
160525
160883
  exports.describeHksvCamera = describeHksvCamera;
160884
+ exports.exportHapActions = exportHapActions;
160526
160885
  exports.initHapStorage = initHapStorage;
160527
160886
  exports.publishStandalone = publishStandalone;
160528
160887
  exports.resolveClipRetentionDays = resolveClipRetentionDays;