@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.
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
- import { spawn } from "node:child_process";
3
2
  import { createHash, randomBytes, randomUUID } from "node:crypto";
3
+ import { spawn } from "node:child_process";
4
4
  import * as path from "node:path";
5
5
  import { join } from "node:path";
6
6
  import { createReadStream, createWriteStream, readFileSync } from "node:fs";
@@ -6021,7 +6021,7 @@ var ZodIssueCode = {
6021
6021
  var ZodFirstPartyTypeKind;
6022
6022
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6023
6023
  //#endregion
6024
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6024
+ //#region ../types/dist/sleep-D1jjWAr8.mjs
6025
6025
  /**
6026
6026
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6027
6027
  * window to float samples (D455).
@@ -6621,7 +6621,7 @@ var NOT_RUN = {
6621
6621
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6622
6622
  * because the hub (and this addon's boot) must not hang on a migration.
6623
6623
  */
6624
- async function runAddonMigrations(host, migrations, logger) {
6624
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6625
6625
  const first = migrations[0];
6626
6626
  if (first === void 0) return NOT_RUN;
6627
6627
  const owner = first.meta.owner;
@@ -6650,7 +6650,9 @@ async function runAddonMigrations(host, migrations, logger) {
6650
6650
  else if (status === "blocked") blocked.push(id);
6651
6651
  else skipped.push(id);
6652
6652
  };
6653
+ const selected = options.only === void 0 ? null : new Set(options.only);
6653
6654
  for (const step of declaration.steps) {
6655
+ if (selected !== null && !selected.has(step.id)) continue;
6654
6656
  const bound = byId.get(step.id);
6655
6657
  if (bound === void 0 || step.action === "skip") {
6656
6658
  skipped.push(step.id);
@@ -7810,14 +7812,18 @@ var BaseAddon = class {
7810
7812
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7811
7813
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7812
7814
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7815
+ *
7816
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7817
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7818
+ * omitted applied ids "newer").
7813
7819
  */
7814
- async runMigrations(migrations) {
7820
+ async runMigrations(migrations, options) {
7815
7821
  const api = this.ctx.api.migrations;
7816
7822
  const report = await runAddonMigrations({
7817
7823
  declareOwner: (input) => api.declareOwner.mutate(input),
7818
7824
  startMigration: (input) => api.startMigration.mutate(input),
7819
7825
  finishMigration: (input) => api.finishMigration.mutate(input)
7820
- }, migrations, this.ctx.logger);
7826
+ }, migrations, this.ctx.logger, options);
7821
7827
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7822
7828
  return report;
7823
7829
  }
@@ -9275,6 +9281,7 @@ function defineEntryKind(name, spec) {
9275
9281
  class: "config",
9276
9282
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9277
9283
  retention: { none: "an entry goes only when the operator deletes it" },
9284
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9278
9285
  ...spec.database === void 0 ? {} : { database: spec.database },
9279
9286
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9280
9287
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -9971,6 +9978,28 @@ function toNodeId(idOrRunnerId) {
9971
9978
  const head = idOrRunnerId.split("/")[0];
9972
9979
  return head === void 0 || head.length === 0 ? idOrRunnerId : head;
9973
9980
  }
9981
+ /**
9982
+ * Identity — preserves literal types for downstream inference.
9983
+ *
9984
+ * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9985
+ * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9986
+ * the broader unions declared on `CustomActionSpec`'s default generics.
9987
+ * Shape validity is enforced separately by the `customAction(...)` helper
9988
+ * whose return type is already a `CustomActionSpec<...>`.
9989
+ */
9990
+ function defineCustomActions(spec) {
9991
+ return spec;
9992
+ }
9993
+ function customAction(input, output, options) {
9994
+ return {
9995
+ input,
9996
+ output,
9997
+ kind: options?.kind ?? "query",
9998
+ auth: options?.auth ?? "protected",
9999
+ scope: options?.scope ?? { kind: "system" },
10000
+ ...options?.caller ? { caller: "required" } : {}
10001
+ };
10002
+ }
9974
10003
  Object.freeze({ "doorbell": "lastPressedAt" });
9975
10004
  /** Every capability name, so addon code can check a name without the schema graph. */
9976
10005
  var CAP_NAMES = Object.freeze([
@@ -11999,7 +12028,7 @@ object({
11999
12028
  params: record(string(), union([string(), number()])).optional()
12000
12029
  });
12001
12030
  //#endregion
12002
- //#region ../types/dist/composition-CRNwcFYY.mjs
12031
+ //#region ../types/dist/composition-pOHbTzRB.mjs
12003
12032
  var AUDIO_ENCODER_BY_CODEC = {
12004
12033
  opus: "libopus",
12005
12034
  aac: "aac",
@@ -15256,7 +15285,13 @@ var MigrationLedgerEntrySchema = object({
15256
15285
  * joined by the engine from the catalogues it knows this boot. Absent when no
15257
15286
  * catalogue lists the id (a newer database).
15258
15287
  */
15259
- meta: MigrationMetaSchema.optional()
15288
+ meta: MigrationMetaSchema.optional(),
15289
+ /**
15290
+ * Set when this is an applied row of an addon owner whose catalogue the answering
15291
+ * process has not loaded (the owner has not declared yet): the row is applied, the
15292
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
15293
+ */
15294
+ ownerNotLoaded: boolean().optional()
15260
15295
  });
15261
15296
  /** A catalogued migration that is not applied, with where it stands. */
15262
15297
  var MigrationPendingEntrySchema = object({
@@ -50004,6 +50039,9 @@ var RunningProposalEvidenceSchema = object({
50004
50039
  runsFound: number().int().nonnegative(),
50005
50040
  pausesFound: number().int().nonnegative(),
50006
50041
  longestPauseMs: number().nonnegative(),
50042
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
50043
+ pulsesFound: number().int().nonnegative(),
50044
+ longestPulseMs: number().nonnegative(),
50007
50045
  idleFloorW: number(),
50008
50046
  noiseCeilingW: number(),
50009
50047
  plateauW: number(),
@@ -51230,13 +51268,6 @@ var ExportInstanceUnknownError = class extends Error {
51230
51268
  function statusInstanceOf(input) {
51231
51269
  return "instanceId" in input ? input.instanceId : void 0;
51232
51270
  }
51233
- /**
51234
- * A single-instance provider's check: an absent id or its own passes, any other throws
51235
- * `ExportInstanceUnknownError`.
51236
- */
51237
- function assertOwnExportInstance(addon, own, instanceId) {
51238
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
51239
- }
51240
51271
  var LinkStateSchema = _enum([
51241
51272
  "unlinked",
51242
51273
  "linked",
@@ -55088,6 +55119,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
55088
55119
  }), object({ success: boolean() }), {
55089
55120
  kind: "mutation",
55090
55121
  auth: "admin"
55122
+ }), method(object({ id: string() }), object({
55123
+ rows: number().int().nonnegative(),
55124
+ secrets: number().int().nonnegative()
55125
+ }), {
55126
+ kind: "mutation",
55127
+ auth: "admin"
55091
55128
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
55092
55129
  addonId: string(),
55093
55130
  settings: record(string(), unknown())
@@ -77187,11 +77224,15 @@ discriminatedUnion("kind", [object({
77187
77224
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
77188
77225
  * near F. A device that is not near one level most of the time has no floor.
77189
77226
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
77190
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
77191
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
77227
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
77228
+ * display waking): it is neither a run nor a pause. Among the remaining
77229
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
77230
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
77231
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
77232
+ * is no run.
77192
77233
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
77193
- * grid a person would type; stop dwell covers the longest pause; start dwell
77194
- * covers the longest standby blip above T.
77234
+ * grid a person would type; stop dwell covers the longest pause and the
77235
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
77195
77236
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
77196
77237
  * run must hold exactly one true interval and nothing may flap outside.
77197
77238
  */
@@ -77202,6 +77243,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
77202
77243
  30 * SECOND_MS;
77203
77244
  60 * SECOND_MS;
77204
77245
  20 * MINUTE_MS$1;
77246
+ 90 * SECOND_MS;
77247
+ 30 * MINUTE_MS$1;
77248
+ 10 * MINUTE_MS$1;
77249
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
77205
77250
  10 * SECOND_MS;
77206
77251
  10 * SECOND_MS;
77207
77252
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -80922,6 +80967,13 @@ Object.freeze({
80922
80967
  access: "create",
80923
80968
  role: "admin"
80924
80969
  },
80970
+ "integrations.clearSettings": {
80971
+ capName: "integrations",
80972
+ capScope: "system",
80973
+ addonId: null,
80974
+ access: "delete",
80975
+ role: "admin"
80976
+ },
80925
80977
  "integrations.create": {
80926
80978
  capName: "integrations",
80927
80979
  capScope: "system",
@@ -92240,6 +92292,17 @@ object({
92240
92292
  delay: number().nonnegative().optional(),
92241
92293
  commands: record(string(), unknown())
92242
92294
  });
92295
+ //#endregion
92296
+ //#region src/custom-actions.ts
92297
+ /**
92298
+ * HomeKit Export — customActions catalog. `regenerateBridge` is the instance form's
92299
+ * "Regenerate setup code" button (`addon-action-button`, `paramsStatic.instanceId`); admin only,
92300
+ * because it unpairs every controller of the bridge.
92301
+ */
92302
+ var exportHapActions = defineCustomActions({ regenerateBridge: customAction(object({ instanceId: string().min(1) }), object({ regenerated: boolean() }), {
92303
+ kind: "mutation",
92304
+ auth: "admin"
92305
+ }) });
92243
92306
  process.platform, process.env["SystemRoot"];
92244
92307
  var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
92245
92308
  /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
@@ -139139,14 +139202,60 @@ function clearPairingFiles(accessoryUuid, logger) {
139139
139202
  } });
139140
139203
  }
139141
139204
  }
139205
+ //#endregion
139206
+ //#region src/hap-instance-kinds.ts
139207
+ /**
139208
+ * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139209
+ * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139210
+ * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139211
+ * the row). The directory its pairing state lives in is derived from the id, never stored
139212
+ * (`hapPersistDirOf`). The default instance is keyed by the
139213
+ * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139214
+ * controller that paired before keeps working.
139215
+ */
139216
+ /** The default instance keeps its record under the addon id (it adopted the old identity). */
139217
+ var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139218
+ /**
139219
+ * What an instance adds to the identity seed of every accessory it publishes. EMPTY for the
139220
+ * default instance (and for no instance at all), which keeps the legacy seed byte for byte so no
139221
+ * paired controller has to pair again; any other instance is salted with its id, so one camera
139222
+ * exposed by two bridges is two different HomeKit accessories, never one colliding MAC.
139223
+ */
139224
+ function instanceSalt(instanceId) {
139225
+ return instanceId === void 0 || instanceId === "export-hap" ? "" : `:instance:${instanceId}`;
139226
+ }
139227
+ /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139228
+ var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139229
+ /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139230
+ function hapPersistDirOf(instanceId) {
139231
+ return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139232
+ }
139233
+ var hapBridgesKind = defineEntryKind("hap-bridges", {
139234
+ title: "HomeKit bridge",
139235
+ nameField: "name",
139236
+ schema: object({
139237
+ name: string().min(1),
139238
+ username: string().min(1),
139239
+ uuid: string().min(1),
139240
+ pincode: string().min(1).meta({ secret: true }),
139241
+ enabled: boolean().optional()
139242
+ })
139243
+ });
139244
+ function identityOfBody(body) {
139245
+ return {
139246
+ username: body.username,
139247
+ uuid: body.uuid,
139248
+ pincode: body.pincode
139249
+ };
139250
+ }
139142
139251
  /** Deterministic and distinct from every device accessory uuid. */
139143
- function actionSwitchUuid(actionId) {
139144
- return import_dist.uuid.generate(`camstack:hap:action:${actionId}`);
139252
+ function actionSwitchUuid(actionId, instanceId) {
139253
+ return import_dist.uuid.generate(`camstack:hap:action:${actionId}${instanceSalt(instanceId)}`);
139145
139254
  }
139146
139255
  function buildActionSwitch(input) {
139147
139256
  const { actionId, displayName, run } = input;
139148
139257
  const autoOffMs = input.autoOffMs ?? 1e3;
139149
- const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId));
139258
+ const accessory = new import_dist.Accessory(displayName, actionSwitchUuid(actionId, input.instanceId));
139150
139259
  accessory.category = import_dist.Categories.SWITCH;
139151
139260
  const info = accessory.getService(import_dist.Service.AccessoryInformation);
139152
139261
  info?.setCharacteristic(import_dist.Characteristic.Manufacturer, "CamStack");
@@ -139220,6 +139329,10 @@ var ActionExports = class {
139220
139329
  exposedAs: e.displayName
139221
139330
  }));
139222
139331
  }
139332
+ /** Every accessory currently published for an action (to wipe their pairing state). */
139333
+ accessoryUuids() {
139334
+ return [...this.mappers.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139335
+ }
139223
139336
  /** Re-publish the persisted selection (boot). One failure does not stop the rest. */
139224
139337
  async attachAll() {
139225
139338
  for (const entry of this.entries) try {
@@ -139287,6 +139400,7 @@ var ActionExports = class {
139287
139400
  const mapper = buildActionSwitch({
139288
139401
  actionId: entry.actionId,
139289
139402
  displayName: entry.displayName,
139403
+ instanceId: this.ports.instanceId,
139290
139404
  run: async () => {
139291
139405
  await runExportedAction(this.ports.api, this.ports.logger, {
139292
139406
  exporter: EXPORTER,
@@ -139427,6 +139541,128 @@ var BridgeHost = class {
139427
139541
  }
139428
139542
  };
139429
139543
  //#endregion
139544
+ //#region src/mappers/kind.ts
139545
+ /**
139546
+ * Which orchestrator a device gets, which device types the picker offers, and
139547
+ * what a device's HomeKit accessory is called on the wire.
139548
+ *
139549
+ * Separate from `index.ts` (the factory registry) only so the orchestrators can
139550
+ * import the uuid convention without importing the registry that imports them.
139551
+ */
139552
+ var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
139553
+ /**
139554
+ * The device types the Export picker offers, and the answer to the cap's
139555
+ * `listSupportedDeviceKinds`.
139556
+ *
139557
+ * A UI FILTER, nothing more. Whether a device actually exports anything is
139558
+ * decided by its capabilities (`rowsForCaps` in the capability table) — the
139559
+ * doctrine the HA exporter writes down, and the thing that confined the
139560
+ * previous exporter to cameras when it was ignored.
139561
+ *
139562
+ * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
139563
+ * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
139564
+ * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
139565
+ * absent — each needs a service whose semantics the table cannot yet honour,
139566
+ * and offering the tab before the mapping exists is how an operator gets an
139567
+ * accessory that pairs and does nothing.
139568
+ *
139569
+ * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
139570
+ * (`builders/generic/security-system.ts`), and the two things the table could
139571
+ * not previously honour are now honoured explicitly: HomeKit is only ever
139572
+ * offered the arm modes the panel accepts, and a panel that requires a PIN
139573
+ * refuses the write out loud instead of pretending to arm.
139574
+ */
139575
+ var HAP_EXPORTABLE_DEVICE_TYPES = [
139576
+ DeviceType.Camera,
139577
+ DeviceType.Light,
139578
+ DeviceType.Switch,
139579
+ DeviceType.Siren,
139580
+ DeviceType.Sensor,
139581
+ DeviceType.Lock,
139582
+ DeviceType.Presence,
139583
+ DeviceType.AlarmPanel,
139584
+ DeviceType.Generic
139585
+ ];
139586
+ /**
139587
+ * Resolve the orchestrator for a device from its TYPE.
139588
+ *
139589
+ * `null` means "no Export tab": the picker must not offer a type no
139590
+ * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
139591
+ * to `camera` — that is what every entry persisted before this function existed
139592
+ * carries, and a transient API failure must never re-shape an exposed camera.
139593
+ */
139594
+ function pickMapperKind(deviceType) {
139595
+ if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
139596
+ if (deviceType === DeviceType.Camera) return "camera";
139597
+ const withheld = applianceExport("homekit", deviceType);
139598
+ if (withheld !== null && !withheld.exported) return null;
139599
+ return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
139600
+ }
139601
+ /**
139602
+ * The deterministic HAP accessory UUID for a device.
139603
+ *
139604
+ * One function, because three call sites depend on the answer agreeing: the
139605
+ * orchestrator that builds the accessory, `unexposeDevice` (which wipes
139606
+ * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
139607
+ * and the export sync state that records it.
139608
+ *
139609
+ * The camera namespace is FROZEN — every camera paired to date derives its MAC
139610
+ * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
139611
+ * would make every paired camera a stranger. Generic devices get their own
139612
+ * namespace so a switch and a camera that happen to share a device id are not
139613
+ * the same HomeKit accessory.
139614
+ */
139615
+ function accessoryUuidFor(kind, deviceId, instanceId) {
139616
+ const seed = kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`;
139617
+ return import_dist.uuid.generate(`${seed}${instanceSalt(instanceId)}`);
139618
+ }
139619
+ //#endregion
139620
+ //#region src/bridge-instance.ts
139621
+ var BridgeInstance = class {
139622
+ id;
139623
+ name;
139624
+ identity;
139625
+ bridgeHost;
139626
+ exposure;
139627
+ /** The devices of this bridge that have a live accessory, by device id. */
139628
+ exposed = /* @__PURE__ */ new Map();
139629
+ /** Pending rebuild timers per device id: debounce, cleared on detach. */
139630
+ pendingRebuildTimers = /* @__PURE__ */ new Map();
139631
+ actionExports = null;
139632
+ /** Last advertised export fingerprints (the reconcile cache) of a NON-default bridge; the default one persists its own. */
139633
+ syncState = /* @__PURE__ */ new Map();
139634
+ constructor(id, name, identity, bridgeHost, exposure) {
139635
+ this.id = id;
139636
+ this.name = name;
139637
+ this.identity = identity;
139638
+ this.bridgeHost = bridgeHost;
139639
+ this.exposure = exposure;
139640
+ }
139641
+ get pincode() {
139642
+ return this.identity.pincode;
139643
+ }
139644
+ findEntry(deviceId) {
139645
+ const id = String(deviceId);
139646
+ return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
139647
+ }
139648
+ /** The HAP accessory uuid this bridge gives a device (`accessoryUuidFor`, salted per bridge). */
139649
+ accessoryUuidOf(kind, deviceId) {
139650
+ return accessoryUuidFor(kind, deviceId, this.id);
139651
+ }
139652
+ /**
139653
+ * Every accessory uuid whose pairing state belongs to this bridge: the bridge itself, each live
139654
+ * accessory of a device and each exported action. What a Regenerate or a delete must wipe.
139655
+ */
139656
+ pairingUuids() {
139657
+ const fromDevices = [...this.exposed.values()].flatMap((m) => m.accessories.map((a) => a.UUID));
139658
+ return [
139659
+ this.identity.uuid,
139660
+ ...fromDevices,
139661
+ ...this.actionExports?.accessoryUuids() ?? []
139662
+ ];
139663
+ }
139664
+ };
139665
+ //#endregion
139430
139666
  //#region src/exposed-entry.ts
139431
139667
  /**
139432
139668
  * Carrying an exposed-device entry across a re-expose.
@@ -139513,81 +139749,31 @@ var hapBridgeExportsKind = defineEntryKind("hap-bridge-exports", {
139513
139749
  /** The settings keys that moved into the record; the migrations name them. */
139514
139750
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
139515
139751
  //#endregion
139516
- //#region src/hap-instance-kinds.ts
139517
- /**
139518
- * The HomeKit export's instances as records (D985, D996): one `hap-bridges` row per bridge
139519
- * identity, owned by `export-hap`. A row IS what a paired controller knows the bridge by: the
139520
- * MAC-style `username`, the bridge `uuid` and the setup code (`pincode`, a keychain marker bound to
139521
- * the row). The directory its pairing state lives in is derived from the id, never stored
139522
- * (`hapPersistDirOf`). The default instance is keyed by the
139523
- * addon id and ADOPTS the identity the addon held in its settings, byte for byte, so a
139524
- * controller that paired before keeps working.
139525
- */
139526
- /** The default instance keeps its record under the addon id (it adopted the old identity). */
139527
- var HAP_DEFAULT_INSTANCE_ID = "export-hap";
139528
- /** Where the pairing state of the default instance has always lived, under the addon data dir. */
139529
- var HAP_DEFAULT_PERSIST_DIR = "hap-store";
139530
- /** The pairing-state directory of an instance, relative to the addon data dir: derived, not stored. */
139531
- function hapPersistDirOf(instanceId) {
139532
- return instanceId === "export-hap" ? HAP_DEFAULT_PERSIST_DIR : `hap-store-${instanceId}`;
139533
- }
139534
- var hapBridgesKind = defineEntryKind("hap-bridges", {
139535
- title: "HomeKit bridge",
139536
- nameField: "name",
139537
- schema: object({
139538
- name: string().min(1),
139539
- username: string().min(1),
139540
- uuid: string().min(1),
139541
- pincode: string().min(1).meta({ secret: true }),
139542
- enabled: boolean().optional()
139543
- })
139544
- });
139545
- function identityOfBody(body) {
139546
- return {
139547
- username: body.username,
139548
- uuid: body.uuid,
139549
- pincode: body.pincode
139550
- };
139551
- }
139552
- //#endregion
139553
139752
  //#region src/hap-identity.ts
139554
139753
  /**
139555
- * Which HomeKit bridge identity the addon boots with: the default instance record, and nothing
139556
- * else. There is no fallback to the settings the identity once lived in; the migration moved it.
139557
- * A fresh identity is minted only when no record exists AND no legacy identity is still stored.
139558
- * A legacy identity without a record means the migration did not finish, and minting then would
139559
- * unpair every controller, so the addon refuses to boot with the reason.
139754
+ * Whether the DEFAULT HomeKit bridge exists at boot, and with which identity: the default instance
139755
+ * record, and nothing else. There is no fallback to the settings the identity once lived in; the
139756
+ * migration moved it. A fresh default identity is minted only when no default record exists, no
139757
+ * other bridge exists (the operator may have deleted the default one on purpose) AND no legacy
139758
+ * identity is still stored. A legacy identity without a record means the migration did not finish,
139759
+ * and minting then would unpair every controller, so the addon refuses to boot with the reason.
139760
+ *
139761
+ * Every other instance is read as it is stored; this module is only about the default one.
139560
139762
  */
139561
- /** An operator-supplied `fixedPin` overrides the pincode, never the username/uuid. */
139562
- async function resolveBridgeIdentity(fixedPin, ports) {
139763
+ async function resolveDefaultBridge(ports) {
139563
139764
  const stored = await ports.readRecord();
139564
139765
  if (stored.kind === "unavailable") throw new Error("export-hap: the bridge identity exists but the keychain cannot serve it");
139565
- if (stored.kind === "resolved") {
139566
- if (fixedPin !== null && fixedPin !== stored.body.pincode) {
139567
- await ports.patchPincode(fixedPin);
139568
- return {
139569
- identity: identityOfBody({
139570
- ...stored.body,
139571
- pincode: fixedPin
139572
- }),
139573
- minted: false
139574
- };
139575
- }
139576
- return {
139577
- identity: identityOfBody(stored.body),
139578
- minted: false
139579
- };
139580
- }
139581
- if (await ports.legacyIdentityPresent()) throw new Error("export-hap: a bridge identity is still in the old settings but its instance record does not exist; the identity migration did not complete. Refusing to boot: a new identity would unpair every HomeKit controller");
139582
- const fresh = ports.mint();
139583
- const body = fixedPin === null ? fresh : {
139584
- ...fresh,
139585
- pincode: fixedPin
139766
+ if (stored.kind === "resolved") return {
139767
+ kind: "existing",
139768
+ identity: identityOfBody(stored.body)
139586
139769
  };
139770
+ 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");
139771
+ if (await ports.otherBridgesExist()) return { kind: "none" };
139772
+ const body = ports.mint();
139587
139773
  await ports.putFresh(body);
139588
139774
  return {
139589
- identity: identityOfBody(body),
139590
- minted: true
139775
+ kind: "minted",
139776
+ identity: identityOfBody(body)
139591
139777
  };
139592
139778
  }
139593
139779
  //#endregion
@@ -139814,12 +140000,87 @@ function legacyIdentityOf(value) {
139814
140000
  };
139815
140001
  }
139816
140002
  //#endregion
140003
+ //#region src/migrations/bridge-name-to-instance.ts
140004
+ async function moveBridgeNameToInstance(ports) {
140005
+ const name = (await ports.readBridgeName()).trim();
140006
+ if (name === "") return {
140007
+ outcome: "already-done",
140008
+ summary: { renamed: false }
140009
+ };
140010
+ const held = await ports.readDefaultRecord();
140011
+ if (held === null || held.name === name) return {
140012
+ outcome: "already-done",
140013
+ summary: { renamed: false }
140014
+ };
140015
+ await ports.patchDefaultName(name);
140016
+ const after = await ports.readDefaultRecord();
140017
+ if (after === null || after.name !== name) throw new Error("the HomeKit default instance does not carry the name it adopted");
140018
+ return {
140019
+ outcome: "done",
140020
+ summary: { renamed: true }
140021
+ };
140022
+ }
140023
+ //#endregion
140024
+ //#region src/migrations/drop-global-knobs.ts
140025
+ /**
140026
+ * The retired global knobs of the HomeKit export. `bridgeName` is the instance's name and
140027
+ * `fixedPin` was an operator-typed setup code (a bridge's setup code is read-only now and changes
140028
+ * only through Regenerate); the bare `interfaceName` is the cluster copy of a setting that is a
140029
+ * fact of one node, which the node row carries since the per-node migration.
140030
+ *
140031
+ * Two bodies, in this order, because a secret must be released before its row goes (the
140032
+ * keychain value would be orphaned otherwise):
140033
+ * 1. `clearFixedPin` (procedure): the keychain value and marker of `fixedPin`;
140034
+ * 2. `planDropGlobalKnobRows` (plan): the rows `bridgeName`, `fixedPin` and the bare
140035
+ * `interfaceName`. The bare interfaceName goes only when the node row exists, so deleting it
140036
+ * can never lose the value. A `@<nodeId>` row is never touched.
140037
+ */
140038
+ async function clearFixedPin(ports) {
140039
+ if (!("fixedPin" in await ports.readStored(["fixedPin"]))) return {
140040
+ outcome: "already-done",
140041
+ summary: { cleared: false }
140042
+ };
140043
+ await ports.clearFixedPin();
140044
+ return {
140045
+ outcome: "done",
140046
+ summary: { cleared: true }
140047
+ };
140048
+ }
140049
+ async function planDropGlobalKnobRows(addonId, ports) {
140050
+ const stored = await ports.readStored([
140051
+ "bridgeName",
140052
+ "fixedPin",
140053
+ "interfaceName",
140054
+ nodeKeyOf("interfaceName")
140055
+ ]);
140056
+ const present = [
140057
+ "bridgeName",
140058
+ "fixedPin",
140059
+ "interfaceName"
140060
+ ].filter((key) => key in stored && (key !== "interfaceName" || nodeKeyOf("interfaceName") in stored));
140061
+ if (present.length === 0) return { edits: [] };
140062
+ const rowId = (key) => `${addonId}.${key}`;
140063
+ return { edits: [{
140064
+ op: "deleteKeys",
140065
+ scope: ADDON_SETTINGS_TABLE,
140066
+ keys: present.map(rowId),
140067
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
140068
+ addonId,
140069
+ key,
140070
+ value: stored[key]
140071
+ }])))
140072
+ }] };
140073
+ }
140074
+ //#endregion
139817
140075
  //#region src/migrations/index.ts
139818
140076
  var EXPORT_HAP_ID = "export-hap";
139819
140077
  var INTERFACE_NAME_PER_NODE_ID = "export-hap/2026-11-03-interface-name-per-node";
139820
140078
  var FIXED_PIN_TO_KEYCHAIN_ID = "export-hap/2026-11-03-fixed-pin-to-keychain";
139821
140079
  var IDENTITY_TO_INSTANCE_ID = "export-hap/2026-11-04-identity-to-default-instance";
139822
140080
  var EXPOSURE_TO_RECORD_ID = "export-hap/2026-11-04-exposure-to-record";
140081
+ var DROP_EXPOSURE_KEYS_ID = "export-hap/2026-11-04-drop-exposure-keys";
140082
+ var BRIDGE_NAME_TO_INSTANCE_ID = "export-hap/2026-11-04-bridge-name-to-instance";
140083
+ var DROP_GLOBAL_KNOBS_ID = "export-hap/2026-11-04-drop-global-knobs";
139823
140084
  /** The `export-hap` catalogue (D987): offered to the engine when the addon initialises. */
139824
140085
  var ADDON_MIGRATIONS = [
139825
140086
  {
@@ -139888,7 +140149,7 @@ var ADDON_MIGRATIONS = [
139888
140149
  },
139889
140150
  {
139890
140151
  meta: {
139891
- id: "export-hap/2026-11-04-drop-exposure-keys",
140152
+ id: DROP_EXPOSURE_KEYS_ID,
139892
140153
  owner: EXPORT_HAP_ID,
139893
140154
  level: "addon-state",
139894
140155
  seq: 5,
@@ -139901,6 +140162,58 @@ var ADDON_MIGRATIONS = [
139901
140162
  fixtureMark: "the bridge name the migration does not know"
139902
140163
  },
139903
140164
  plan: planDropExposureKeys
140165
+ },
140166
+ {
140167
+ meta: {
140168
+ id: BRIDGE_NAME_TO_INSTANCE_ID,
140169
+ owner: EXPORT_HAP_ID,
140170
+ level: "addon-state",
140171
+ seq: 6,
140172
+ dependsOn: [IDENTITY_TO_INSTANCE_ID],
140173
+ store: "settings",
140174
+ scope: "cluster",
140175
+ onFailure: "block-owner",
140176
+ bodyKind: "procedure",
140177
+ description: "Make the installation name the name of the default HomeKit instance record, verified by read-back",
140178
+ fixtureMark: "the bridge name the migration does not know"
140179
+ },
140180
+ procedure: moveBridgeNameToInstance
140181
+ },
140182
+ {
140183
+ meta: {
140184
+ id: DROP_GLOBAL_KNOBS_ID,
140185
+ owner: EXPORT_HAP_ID,
140186
+ level: "addon-state",
140187
+ seq: 7,
140188
+ dependsOn: [FIXED_PIN_TO_KEYCHAIN_ID, IDENTITY_TO_INSTANCE_ID],
140189
+ store: "settings",
140190
+ scope: "cluster",
140191
+ onFailure: "tolerate",
140192
+ bodyKind: "procedure",
140193
+ description: "Release the retired fixed setup code from the keychain: a bridge setup code is read-only now",
140194
+ fixtureMark: "the bridge name the migration does not know"
140195
+ },
140196
+ procedure: clearFixedPin
140197
+ },
140198
+ {
140199
+ meta: {
140200
+ id: "export-hap/2026-11-04-drop-global-knob-rows",
140201
+ owner: EXPORT_HAP_ID,
140202
+ level: "addon-state",
140203
+ seq: 8,
140204
+ dependsOn: [
140205
+ BRIDGE_NAME_TO_INSTANCE_ID,
140206
+ DROP_GLOBAL_KNOBS_ID,
140207
+ INTERFACE_NAME_PER_NODE_ID
140208
+ ],
140209
+ store: "settings",
140210
+ scope: "cluster",
140211
+ onFailure: "tolerate",
140212
+ bodyKind: "plan",
140213
+ description: "Delete the retired bridgeName, fixedPin and cluster interfaceName rows; the node rows are untouched",
140214
+ fixtureMark: "the bridge name the migration does not know"
140215
+ },
140216
+ plan: (ports) => planDropGlobalKnobRows(EXPORT_HAP_ID, ports)
139904
140217
  }
139905
140218
  ];
139906
140219
  //#endregion
@@ -157995,81 +158308,6 @@ function errMsg$3(err) {
157995
158308
  return err instanceof Error ? err.message : String(err);
157996
158309
  }
157997
158310
  //#endregion
157998
- //#region src/mappers/kind.ts
157999
- /**
158000
- * Which orchestrator a device gets, which device types the picker offers, and
158001
- * what a device's HomeKit accessory is called on the wire.
158002
- *
158003
- * Separate from `index.ts` (the factory registry) only so the orchestrators can
158004
- * import the uuid convention without importing the registry that imports them.
158005
- */
158006
- var SUPPORTED_MAPPER_KINDS = ["camera", "generic"];
158007
- /**
158008
- * The device types the Export picker offers, and the answer to the cap's
158009
- * `listSupportedDeviceKinds`.
158010
- *
158011
- * A UI FILTER, nothing more. Whether a device actually exports anything is
158012
- * decided by its capabilities (`rowsForCaps` in the capability table) — the
158013
- * doctrine the HA exporter writes down, and the thing that confined the
158014
- * previous exporter to cameras when it was ignored.
158015
- *
158016
- * Tier A plus `alarm-panel`: the types whose HomeKit services exist today and
158017
- * need no feature-dependent shape. `cover`, `climate`, `fan`, `valve`,
158018
- * `humidifier`, `water-heater`, `button` and `media-player` are deliberately
158019
- * absent — each needs a service whose semantics the table cannot yet honour,
158020
- * and offering the tab before the mapping exists is how an operator gets an
158021
- * accessory that pairs and does nothing.
158022
- *
158023
- * `alarm-panel` is no longer one of them. It maps to `Service.SecuritySystem`
158024
- * (`builders/generic/security-system.ts`), and the two things the table could
158025
- * not previously honour are now honoured explicitly: HomeKit is only ever
158026
- * offered the arm modes the panel accepts, and a panel that requires a PIN
158027
- * refuses the write out loud instead of pretending to arm.
158028
- */
158029
- var HAP_EXPORTABLE_DEVICE_TYPES = [
158030
- DeviceType.Camera,
158031
- DeviceType.Light,
158032
- DeviceType.Switch,
158033
- DeviceType.Siren,
158034
- DeviceType.Sensor,
158035
- DeviceType.Lock,
158036
- DeviceType.Presence,
158037
- DeviceType.AlarmPanel,
158038
- DeviceType.Generic
158039
- ];
158040
- /**
158041
- * Resolve the orchestrator for a device from its TYPE.
158042
- *
158043
- * `null` means "no Export tab": the picker must not offer a type no
158044
- * orchestrator can build. An UNKNOWN type (the device-manager read failed) maps
158045
- * to `camera` — that is what every entry persisted before this function existed
158046
- * carries, and a transient API failure must never re-shape an exposed camera.
158047
- */
158048
- function pickMapperKind(deviceType) {
158049
- if (deviceType === null || deviceType === void 0 || deviceType.length === 0) return "camera";
158050
- if (deviceType === DeviceType.Camera) return "camera";
158051
- const withheld = applianceExport("homekit", deviceType);
158052
- if (withheld !== null && !withheld.exported) return null;
158053
- return HAP_EXPORTABLE_DEVICE_TYPES.find((type) => type === deviceType) === void 0 ? null : "generic";
158054
- }
158055
- /**
158056
- * The deterministic HAP accessory UUID for a device.
158057
- *
158058
- * One function, because three call sites depend on the answer agreeing: the
158059
- * orchestrator that builds the accessory, `unexposeDevice` (which wipes
158060
- * hap-nodejs' pairing blobs by uuid, on a device whose mapper is already gone)
158061
- * and the export sync state that records it.
158062
- *
158063
- * The camera namespace is FROZEN — every camera paired to date derives its MAC
158064
- * from `sha256("camstack:hap:" + uuid)` of this exact string, and changing it
158065
- * would make every paired camera a stranger. Generic devices get their own
158066
- * namespace so a switch and a camera that happen to share a device id are not
158067
- * the same HomeKit accessory.
158068
- */
158069
- function accessoryUuidFor(kind, deviceId) {
158070
- return import_dist.uuid.generate(kind === "camera" ? `camstack:camera:${deviceId}` : `camstack:device:${deviceId}`);
158071
- }
158072
- //#endregion
158073
158311
  //#region src/multi-tier/rtp-streaming-control.ts
158074
158312
  /**
158075
158313
  * `RTP Streaming Control` (0x8045) — start and stop, on the new service.
@@ -158872,7 +159110,7 @@ async function buildCameraAccessory(input) {
158872
159110
  const capNames = new Set(proxy.binding?.entries.map((e) => e.capName) ?? []);
158873
159111
  const isDoorbell = capNames.has("doorbell");
158874
159112
  const category = isDoorbell ? import_dist.Categories.VIDEO_DOORBELL : import_dist.Categories.IP_CAMERA;
158875
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId));
159113
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("camera", numericId, options.instanceId));
158876
159114
  accessory.category = category;
158877
159115
  await populateAccessoryInfo(accessory, proxy, displayName, "Camera");
158878
159116
  const bctx = {
@@ -159007,7 +159245,7 @@ async function buildGenericAccessory(input) {
159007
159245
  const rows = rowsForCaps(capNames);
159008
159246
  if (rows.length === 0) throw new Error(`export-hap: device ${numericId} carries no capability HomeKit can export (bound: ${[...capNames].toSorted().join(", ") || "none"})`);
159009
159247
  const deviceType = await resolveDeviceType(proxy);
159010
- const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId));
159248
+ const accessory = new import_dist.Accessory(displayName, accessoryUuidFor("generic", numericId, options.instanceId));
159011
159249
  accessory.category = accessoryCategoryFor(deviceType);
159012
159250
  await populateAccessoryInfo(accessory, proxy, displayName, "Accessory");
159013
159251
  const bctx = {
@@ -159240,8 +159478,6 @@ var HAP_STREAM_PREFERENCE_OPTIONS = [
159240
159478
  }
159241
159479
  ];
159242
159480
  var DEFAULT_CONFIG = {
159243
- bridgeName: "CamStack Bridge",
159244
- fixedPin: "",
159245
159481
  interfaceName: "",
159246
159482
  clipRetentionDays: 14,
159247
159483
  exportSyncState: {}
@@ -159260,10 +159496,6 @@ var BANNED_PINCODES = new Set([
159260
159496
  "123-45-678",
159261
159497
  "876-54-321"
159262
159498
  ]);
159263
- var PINCODE_REGEX = /^\d{3}-\d{2}-\d{3}$/;
159264
- function isValidPincode(pin) {
159265
- return PINCODE_REGEX.test(pin) && !BANNED_PINCODES.has(pin);
159266
- }
159267
159499
  function generateUsername() {
159268
159500
  const bytes = randomBytes(6);
159269
159501
  return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, "0")).join(":");
@@ -159278,33 +159510,23 @@ function generatePincode() {
159278
159510
  }
159279
159511
  throw new Error("export-hap: failed to generate a non-trivial pincode");
159280
159512
  }
159513
+ var DEFAULT_BRIDGE_NAME = "CamStack Bridge";
159281
159514
  function buildBridgeUuid(bridgeName) {
159282
159515
  return import_dist.uuid.generate(`camstack:bridge:${bridgeName}:${Date.now()}`);
159283
159516
  }
159284
159517
  var ExportHapAddon = class extends BaseAddon {
159285
159518
  /**
159286
- * The old `identity.pincode` secret: declared only so the identity migration can release its
159287
- * keychain entry when it clears the old setting. The identity itself is a record now.
159519
+ * The old `identity.pincode` and `fixedPin` secrets: declared only so the migrations can
159520
+ * release their keychain entries when they clear the old settings. The identity itself is a record now.
159288
159521
  */
159289
- secretStatePaths = ["identity.pincode"];
159290
- exposed = /* @__PURE__ */ new Map();
159291
- /** The exported actions — switches beside the devices (D968). */
159292
- actionExports = null;
159522
+ secretStatePaths = ["identity.pincode", "fixedPin"];
159523
+ /** The running bridges, by instance id: one runtime per ENABLED `hap-bridges` record. */
159524
+ bridges = /* @__PURE__ */ new Map();
159525
+ /** Start / stop / regenerate of bridges run one at a time: they share one HAP storage. */
159526
+ lifecycle = Promise.resolve();
159293
159527
  lastError;
159294
159528
  /** The HomeKit instances (D985): one record per bridge identity. */
159295
159529
  instances = null;
159296
- /**
159297
- * What the bridge exposes: the devices (with their per-device settings) and the actions, held in
159298
- * the `hap-bridge-exports` record of the default instance. The in-memory copy is loaded once at
159299
- * boot and written through on every change; this addon is the record's only writer.
159300
- */
159301
- exposure = {
159302
- name: HAP_EXPOSURE_NAME,
159303
- devices: [],
159304
- actions: []
159305
- };
159306
- /** Shared HAP setup code applied to every published accessory. */
159307
- pincode = "";
159308
159530
  /** Optional mDNS/bind interface (config.interfaceName), or undefined. */
159309
159531
  bind;
159310
159532
  /**
@@ -159348,12 +159570,6 @@ var ExportHapAddon = class extends BaseAddon {
159348
159570
  hksvBuilds = new HksvBuildOutcomes();
159349
159571
  /** The clip byte + still routes. `null` until `onInitialize` has served them. */
159350
159572
  hksvClipPlanes = null;
159351
- /**
159352
- * THE bridge. Lazily created and published the first time a non-camera
159353
- * accessory needs it; never torn down while the addon runs, because an
159354
- * unpublish would drop a pairing the operator already entered a code for.
159355
- */
159356
- bridgeHost = null;
159357
159573
  constructor() {
159358
159574
  super({ ...DEFAULT_CONFIG });
159359
159575
  }
@@ -159367,31 +159583,24 @@ var ExportHapAddon = class extends BaseAddon {
159367
159583
  this.instances = new RecordIntegrationInstances(records, hapBridgesKind, {
159368
159584
  description: {
159369
159585
  role: "services",
159370
- instanceMode: "single",
159586
+ instanceMode: "multiple",
159371
159587
  kind: "bridge",
159372
159588
  canTest: false
159373
159589
  },
159374
- formSchema: () => this.schema({ sections: [] }),
159590
+ formSchema: (id) => this.bridgeForm(id),
159375
159591
  initialBody: (name) => ({
159376
159592
  name,
159377
159593
  username: generateUsername(),
159378
159594
  uuid: buildBridgeUuid(name),
159379
159595
  pincode: generatePincode()
159380
159596
  }),
159381
- configured: (body) => body.username !== "" && body.pincode !== ""
159597
+ mintId: () => `hap-${randomUUID().slice(0, 8)}`,
159598
+ configured: (body) => body.username !== "" && body.pincode !== "",
159599
+ onChanged: (id, change) => this.enqueue(() => this.applyChange(id, change))
159382
159600
  });
159383
159601
  await this.migrateSettings();
159384
- const identity = await this.ensureIdentity();
159385
- await this.loadExposure();
159386
- this.pincode = identity.pincode;
159602
+ await this.ensureDefaultBridge();
159387
159603
  this.bind = this.config.interfaceName || void 0;
159388
- this.bridgeHost = new BridgeHost({
159389
- displayName: this.config.bridgeName,
159390
- uuid: identity.uuid,
159391
- pincode: identity.pincode,
159392
- bind: this.bind,
159393
- logger: this.ctx.logger
159394
- });
159395
159604
  try {
159396
159605
  await initHapStorage(path.join(this.ctx.dataDir, hapPersistDirOf(HAP_DEFAULT_INSTANCE_ID)));
159397
159606
  } catch (err) {
@@ -159405,7 +159614,7 @@ var ExportHapAddon = class extends BaseAddon {
159405
159614
  this.hksvClipStore = new HksvClipStore({
159406
159615
  logger: this.ctx.logger.child("hksv-clips"),
159407
159616
  resolveRoot: () => this.hksvClipLocation?.root() ?? Promise.resolve(null),
159408
- maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159617
+ maxAgeMsFor: (deviceId) => resolveClipRetentionDays(this.instanceForDevice(deviceId)?.findEntry(deviceId)?.settings, this.config.clipRetentionDays) * 24 * 60 * 60 * 1e3,
159409
159618
  mintThumbnail: createClipThumbnailMinter({ runner: createBoundedFfmpegRunner({
159410
159619
  resolveFfmpeg: this.pinnedFfmpeg,
159411
159620
  spawnFn: spawn,
@@ -159418,161 +159627,323 @@ var ExportHapAddon = class extends BaseAddon {
159418
159627
  }) })
159419
159628
  });
159420
159629
  await this.serveHksvClipPlanes();
159630
+ const ordered = (await this.requireInstances().listResolved()).toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159631
+ for (const row of ordered) try {
159632
+ await this.startInstance(row.id);
159633
+ } catch (err) {
159634
+ this.ctx.logger.error("export-hap: bridge failed to start", { meta: {
159635
+ instanceId: row.id,
159636
+ error: errMsg(err)
159637
+ } });
159638
+ }
159639
+ this.ctx.addDisposer(async () => {
159640
+ await this.enqueue(async () => {
159641
+ for (const id of Array.from(this.bridges.keys())) await this.stopInstance(id);
159642
+ });
159643
+ });
159644
+ this.subscribeDeviceProvisionedForReconcile();
159645
+ this.subscribeDeviceReadyForReconcile();
159646
+ this.subscribeStorageLocationsForClips();
159647
+ const provider = this.buildExportProvider();
159648
+ const clipsProvider = createHksvVideoclipsProvider({
159649
+ logger: this.ctx.logger.child("hksv-clips"),
159650
+ addonId: EXPORT_HAP_ADDON_ID,
159651
+ describeCamera: (deviceId) => describeHksvCamera(this.instanceForDevice(deviceId)?.findEntry(deviceId) ?? null, this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.instanceForDevice(deviceId)?.exposed.get(String(deviceId))?.accessories ?? [])),
159652
+ readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159653
+ locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159654
+ mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159655
+ thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159656
+ clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159657
+ });
159658
+ return {
159659
+ providers: [
159660
+ {
159661
+ capability: deviceExportCapability,
159662
+ provider
159663
+ },
159664
+ {
159665
+ capability: videoclipsCapability,
159666
+ provider: clipsProvider
159667
+ },
159668
+ {
159669
+ capability: integrationInstancesCapability,
159670
+ provider: this.requireInstances().toProvider()
159671
+ }
159672
+ ],
159673
+ customActions: exportHapActions,
159674
+ actionHandlers: { regenerateBridge: async ({ instanceId }) => this.regenerateBridge(instanceId) }
159675
+ };
159676
+ }
159677
+ /** Run one start / stop / regenerate at a time: bridges share one HAP storage and one clip store. */
159678
+ enqueue(job) {
159679
+ const run = this.lifecycle.then(job);
159680
+ this.lifecycle = run.then(() => void 0, () => void 0);
159681
+ return run;
159682
+ }
159683
+ /** The bridge that owns a device: the one that exposes it (the default first), else the default, else any. */
159684
+ instanceForDevice(deviceId) {
159685
+ const key = String(deviceId);
159686
+ const ordered = [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159687
+ return ordered.find((b) => b.exposed.has(key)) ?? ordered.find((b) => b.findEntry(deviceId) !== null) ?? ordered[0] ?? null;
159688
+ }
159689
+ requireBridge(instanceId) {
159690
+ const inst = this.bridges.get(instanceId);
159691
+ if (inst === void 0) throw new ExportInstanceUnknownError(EXPORT_HAP_ADDON_ID, instanceId);
159692
+ return inst;
159693
+ }
159694
+ /** Bring a record's runtime up from the record: (re)publish its bridge and every exposed device. */
159695
+ async startInstance(id) {
159696
+ await this.stopInstance(id);
159697
+ const resolved = await this.requireInstances().readResolved(id);
159698
+ if (resolved === null || !resolved.enabled) return;
159699
+ if (resolved.secrets === "unavailable") {
159700
+ this.ctx.logger.error("export-hap: bridge not started — the keychain cannot serve its setup code", { meta: { instanceId: id } });
159701
+ return;
159702
+ }
159703
+ const identity = identityOfBody(resolved.body);
159704
+ const exposure = await this.loadExposure(id);
159705
+ const inst = new BridgeInstance(id, resolved.body.name, identity, new BridgeHost({
159706
+ displayName: resolved.body.name,
159707
+ uuid: identity.uuid,
159708
+ pincode: identity.pincode,
159709
+ bind: this.bind,
159710
+ logger: this.ctx.logger
159711
+ }), exposure);
159712
+ this.bridges.set(id, inst);
159713
+ this.warnOnDuplicateName(inst);
159421
159714
  const validKinds = new Set(SUPPORTED_MAPPER_KINDS);
159422
- const cleaned = this.exposure.devices.filter((entry) => {
159715
+ const cleaned = inst.exposure.devices.filter((entry) => {
159423
159716
  if (validKinds.has(entry.mapperKind)) return true;
159424
159717
  this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) }).info("export-hap: dropping stale exposed entry (unknown mapperKind)", { meta: { mapperKind: entry.mapperKind } });
159425
159718
  return false;
159426
159719
  });
159427
- if (cleaned.length !== this.exposure.devices.length) await this.setExposedDevices(cleaned);
159720
+ if (cleaned.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, cleaned);
159428
159721
  for (const entry of cleaned) {
159429
159722
  const log = this.ctx.logger.withTags({ deviceId: Number.parseInt(entry.deviceId, 10) });
159430
159723
  try {
159431
- await this.attachMapper(entry);
159724
+ await this.attachMapper(inst, entry);
159432
159725
  const numericId = Number.parseInt(entry.deviceId, 10);
159433
159726
  if (Number.isFinite(numericId)) {
159434
- const fp = await this.computeExportFingerprint(numericId);
159435
- if (fp !== null) await this.persistFingerprint(numericId, fp);
159727
+ const fp = await this.computeExportFingerprint(inst, numericId);
159728
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159436
159729
  }
159437
159730
  } catch (err) {
159438
159731
  log.warn("export-hap: failed to re-attach mapper on boot", { meta: { error: errMsg(err) } });
159439
159732
  }
159440
159733
  }
159441
- this.actionExports = new ActionExports({
159734
+ inst.actionExports = new ActionExports({
159442
159735
  api: this.ctx.api,
159443
159736
  logger: this.ctx.logger,
159737
+ instanceId: id,
159444
159738
  publish: async (accessory) => {
159445
- if (this.bridgeHost !== null && await this.bridgeHost.add(accessory)) return;
159739
+ if (await inst.bridgeHost.add(accessory)) return;
159446
159740
  await publishStandalone(accessory, {
159447
- pincode: this.pincode,
159741
+ pincode: inst.pincode,
159448
159742
  port: 0,
159449
159743
  bind: this.bind,
159450
159744
  logger: this.ctx.logger
159451
159745
  });
159452
159746
  },
159453
159747
  unpublish: async (accessory) => {
159454
- if (this.bridgeHost?.holds(accessory) === true) {
159455
- this.bridgeHost.remove(accessory);
159748
+ if (inst.bridgeHost.holds(accessory)) {
159749
+ inst.bridgeHost.remove(accessory);
159456
159750
  return;
159457
159751
  }
159458
159752
  await unpublishAccessory(accessory, this.ctx.logger);
159459
159753
  },
159460
- persist: (entries) => this.setExposedActions(entries)
159461
- }, this.exposure.actions);
159462
- await this.actionExports.attachAll();
159463
- await this.actionExports.reconcile();
159464
- this.ctx.addDisposer(async () => {
159465
- await this.actionExports?.dispose();
159466
- await this.detachAll();
159467
- await this.bridgeHost?.dispose();
159754
+ persist: (entries) => this.setExposedActions(inst, entries)
159755
+ }, inst.exposure.actions);
159756
+ await inst.actionExports.attachAll();
159757
+ await inst.actionExports.reconcile();
159758
+ this.ctx.logger.info("export-hap: bridge started", { meta: {
159759
+ instanceId: id,
159760
+ name: inst.name,
159761
+ devices: inst.exposed.size
159762
+ } });
159763
+ }
159764
+ /** Take a bridge's runtime down. Its pairing files stay: a stop is not a withdrawal. */
159765
+ async stopInstance(id) {
159766
+ const inst = this.bridges.get(id);
159767
+ if (inst === void 0) return;
159768
+ this.bridges.delete(id);
159769
+ for (const timer of inst.pendingRebuildTimers.values()) clearTimeout(timer);
159770
+ inst.pendingRebuildTimers.clear();
159771
+ await inst.actionExports?.dispose();
159772
+ await this.detachAll(inst);
159773
+ await inst.bridgeHost.dispose();
159774
+ }
159775
+ /** A record changed: re-apply it. An edit that moved nothing the bridge publishes republishes nothing. */
159776
+ async applyChange(id, change) {
159777
+ if (change === "deleted") {
159778
+ await this.removeInstance(id);
159779
+ return;
159780
+ }
159781
+ const resolved = await this.requireInstances().readResolved(id);
159782
+ if (resolved === null || !resolved.enabled) {
159783
+ await this.stopInstance(id);
159784
+ return;
159785
+ }
159786
+ const running = this.bridges.get(id);
159787
+ if (change === "updated" && running !== void 0 && resolved.secrets === "resolved") {
159788
+ const next = identityOfBody(resolved.body);
159789
+ if (running.name === resolved.body.name && running.identity.uuid === next.uuid && running.identity.username === next.username && running.identity.pincode === next.pincode) return;
159790
+ }
159791
+ await this.startInstance(id);
159792
+ }
159793
+ /**
159794
+ * A bridge was deleted: unpublish it, wipe the pairing state of every accessory it carried (a
159795
+ * leftover blob makes a re-created accessory advertise as already paired) and drop its exposure.
159796
+ */
159797
+ async removeInstance(id) {
159798
+ const uuids = this.bridges.get(id)?.pairingUuids() ?? [];
159799
+ await this.stopInstance(id);
159800
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159801
+ await this.exposureHandle().delete(id);
159802
+ if (id === "export-hap") await this.updateGlobalSettings({ exportSyncState: {} });
159803
+ this.ctx.logger.info("export-hap: bridge removed", { meta: { instanceId: id } });
159804
+ }
159805
+ /**
159806
+ * "Regenerate" (operator decision): a new setup code, every pairing of this bridge cleared and
159807
+ * the bridge republished. Every controller has to pair again; the instance and its exposed
159808
+ * devices stay.
159809
+ */
159810
+ regenerateBridge(instanceId) {
159811
+ return this.enqueue(async () => {
159812
+ const uuids = this.requireBridge(instanceId).pairingUuids();
159813
+ await this.stopInstance(instanceId);
159814
+ for (const uuid of uuids) clearPairingFiles(uuid, this.ctx.logger);
159815
+ await this.requireRecords().kind(hapBridgesKind).patch(instanceId, { pincode: generatePincode() });
159816
+ await this.startInstance(instanceId);
159817
+ this.ctx.logger.info("export-hap: bridge setup code regenerated; pairings cleared", { meta: {
159818
+ instanceId,
159819
+ accessories: uuids.length
159820
+ } });
159821
+ return { regenerated: true };
159468
159822
  });
159469
- this.subscribeDeviceProvisionedForReconcile();
159470
- this.subscribeDeviceReadyForReconcile();
159471
- this.subscribeStorageLocationsForClips();
159472
- this.disposeSharedRebuildTimers();
159473
- const ownInstance = (instanceId) => assertOwnExportInstance("export-hap", EXPORT_HAP_ADDON_ID, instanceId);
159474
- const provider = {
159475
- getStatus: async (input) => {
159476
- ownInstance(statusInstanceOf(input));
159477
- const anyPaired = Array.from(this.exposed.values()).some((m) => accessoryPaired(m.accessory));
159478
- const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159479
- const setup = this.buildSetupBlock();
159480
- return {
159481
- linkState,
159482
- exposedDeviceCount: this.exposed.size,
159483
- ...this.lastError ? { error: this.lastError } : {},
159484
- ...setup ? { setup } : {}
159485
- };
159486
- },
159487
- listInstances: async () => [{
159488
- instanceId: EXPORT_HAP_ADDON_ID,
159489
- name: "HomeKit",
159490
- enabled: true,
159823
+ }
159824
+ warnOnDuplicateName(inst) {
159825
+ const key = inst.name.trim().toLowerCase();
159826
+ const others = [...this.bridges.values()].filter((b) => b.id !== inst.id && b.name.trim().toLowerCase() === key);
159827
+ if (others.length === 0) return;
159828
+ this.ctx.logger.warn("export-hap: two bridges share a name — iOS Home lists them under the same label", { meta: {
159829
+ instanceId: inst.id,
159830
+ name: inst.name,
159831
+ others: others.map((b) => b.id)
159832
+ } });
159833
+ }
159834
+ /** The instance form: the setup code is READ-ONLY (it changes only through Regenerate). */
159835
+ bridgeForm(id) {
159836
+ const inst = id === null ? void 0 : this.bridges.get(id);
159837
+ let qr = "";
159838
+ try {
159839
+ qr = inst?.bridgeHost.accessory?.setupURI() ?? "";
159840
+ } catch (err) {
159841
+ this.ctx.logger.debug("export-hap: bridge setupURI failed", { meta: {
159842
+ instanceId: id,
159843
+ error: errMsg(err)
159844
+ } });
159845
+ }
159846
+ return this.schema({ sections: [{
159847
+ id: "bridge",
159848
+ title: "HomeKit bridge",
159849
+ 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.",
159850
+ fields: [...inst === void 0 ? [] : [{
159851
+ type: "info",
159852
+ key: "setupCode",
159853
+ label: "Setup code",
159854
+ content: inst.pincode
159855
+ }, ...qr === "" ? [] : [{
159856
+ type: "qr-code",
159857
+ key: "setupQr",
159858
+ label: "Pairing QR",
159859
+ caption: "Scan with the iOS Camera app.",
159860
+ value: qr,
159861
+ size: 192
159862
+ }]], ...id === null ? [] : [{
159863
+ type: "addon-action-button",
159864
+ key: "__regenerate-bridge",
159865
+ label: "Regenerate setup code",
159866
+ 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.",
159867
+ addonId: EXPORT_HAP_ADDON_ID,
159868
+ action: "regenerateBridge",
159869
+ buttonLabel: "Regenerate",
159870
+ variant: "danger",
159871
+ paramsStatic: { instanceId: id },
159872
+ 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."
159873
+ }]]
159874
+ }] });
159875
+ }
159876
+ /** Whole-addon status of the bridges: linked when any is paired. */
159877
+ statusOf(bridges) {
159878
+ const anyPaired = bridges.some((b) => Array.from(b.exposed.values()).some((m) => accessoryPaired(m.accessory)));
159879
+ const linkState = this.lastError ? "error" : anyPaired ? "linked" : "unlinked";
159880
+ const setup = bridges.length > 0 ? this.buildSetupBlock(bridges[0]) : null;
159881
+ return {
159882
+ linkState,
159883
+ exposedDeviceCount: new Set(bridges.flatMap((b) => [...b.exposed.keys()])).size,
159884
+ ...this.lastError ? { error: this.lastError } : {},
159885
+ ...setup ? { setup } : {}
159886
+ };
159887
+ }
159888
+ /** The bridges a read names: one, or (no id) all of them with the default first. */
159889
+ bridgesOf(instanceId) {
159890
+ if (instanceId !== void 0) return [this.requireBridge(instanceId)];
159891
+ return [...this.bridges.values()].toSorted((x, y) => Number(y.id === HAP_DEFAULT_INSTANCE_ID) - Number(x.id === HAP_DEFAULT_INSTANCE_ID));
159892
+ }
159893
+ buildExportProvider() {
159894
+ return {
159895
+ getStatus: async (input) => this.statusOf(this.bridgesOf(statusInstanceOf(input))),
159896
+ listInstances: async () => (await this.requireInstances().listResolved()).map((row) => ({
159897
+ instanceId: row.id,
159898
+ name: row.body.name,
159899
+ enabled: row.enabled,
159491
159900
  kind: "hap-bridge"
159492
- }],
159901
+ })),
159493
159902
  listSupportedDeviceKinds: async ({ instanceId }) => {
159494
- ownInstance(instanceId);
159903
+ this.bridgesOf(instanceId);
159495
159904
  return [...HAP_EXPORTABLE_DEVICE_TYPES];
159496
159905
  },
159497
- listExposedDevices: async ({ instanceId }) => {
159498
- ownInstance(instanceId);
159499
- return Array.from(this.exposed.entries()).map(([deviceId, m]) => {
159500
- const entry = this.exposure.devices.find((e) => e.deviceId === deviceId);
159501
- return {
159502
- deviceId,
159503
- exposedAs: m.accessory.displayName,
159504
- ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159505
- };
159506
- });
159507
- },
159508
- exposeDevice: async ({ instanceId, deviceId, capabilities }) => {
159509
- ownInstance(instanceId);
159510
- return this.exposeDevice(deviceId, capabilities);
159511
- },
159512
- unexposeDevice: async ({ instanceId, deviceId }) => {
159513
- ownInstance(instanceId);
159514
- return this.unexposeDevice(deviceId);
159515
- },
159906
+ listExposedDevices: async ({ instanceId }) => this.bridgesOf(instanceId).flatMap((inst) => Array.from(inst.exposed.entries()).map(([deviceId, m]) => {
159907
+ const entry = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159908
+ return {
159909
+ deviceId,
159910
+ exposedAs: m.accessory.displayName,
159911
+ ...entry?.capabilities ? { capabilities: [...entry.capabilities] } : {}
159912
+ };
159913
+ })),
159914
+ exposeDevice: async ({ instanceId, deviceId, capabilities }) => this.exposeDevice(this.requireBridge(instanceId), deviceId, capabilities),
159915
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(this.requireBridge(instanceId), deviceId),
159516
159916
  listSupportedEntityKinds: async () => ["device", "action"],
159517
159917
  listExposedEntities: async ({ instanceId }) => {
159518
- ownInstance(instanceId);
159519
- await this.actionExports?.reconcile();
159520
- return [...Array.from(this.exposed.entries()).map(([deviceId, m]) => ({
159521
- entity: {
159522
- kind: "device",
159523
- deviceId
159524
- },
159525
- exposedAs: m.accessory.displayName
159526
- })), ...this.actionExports?.list() ?? []];
159918
+ const out = [];
159919
+ for (const inst of this.bridgesOf(instanceId)) {
159920
+ await inst.actionExports?.reconcile();
159921
+ out.push(...Array.from(inst.exposed.entries()).map(([deviceId, m]) => ({
159922
+ entity: {
159923
+ kind: "device",
159924
+ deviceId
159925
+ },
159926
+ exposedAs: m.accessory.displayName
159927
+ })), ...inst.actionExports?.list() ?? []);
159928
+ }
159929
+ return out;
159527
159930
  },
159528
159931
  exposeEntity: async ({ instanceId, entity }) => {
159529
- ownInstance(instanceId);
159530
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
159531
- if (entity.kind === "action") return this.requireActionExports().expose(entity.actionId);
159932
+ const inst = this.requireBridge(instanceId);
159933
+ if (entity.kind === "device") return this.exposeDevice(inst, entity.deviceId);
159934
+ if (entity.kind === "action") return this.requireActionExports(inst).expose(entity.actionId);
159532
159935
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159533
159936
  },
159534
159937
  unexposeEntity: async ({ instanceId, entity }) => {
159535
- ownInstance(instanceId);
159536
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
159537
- if (entity.kind === "action") return this.requireActionExports().unexpose(entity.actionId);
159938
+ const inst = this.requireBridge(instanceId);
159939
+ if (entity.kind === "device") return this.unexposeDevice(inst, entity.deviceId);
159940
+ if (entity.kind === "action") return this.requireActionExports(inst).unexpose(entity.actionId);
159538
159941
  throw new Error("export-hap: a notification target cannot be exported to HomeKit");
159539
159942
  },
159540
159943
  getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(input.deviceId),
159541
159944
  getDeviceLiveContribution: async () => null,
159542
159945
  applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(input.deviceId, input.patch)
159543
159946
  };
159544
- const clipsProvider = createHksvVideoclipsProvider({
159545
- logger: this.ctx.logger.child("hksv-clips"),
159546
- addonId: EXPORT_HAP_ADDON_ID,
159547
- describeCamera: (deviceId) => describeHksvCamera(this.findEntry(deviceId), this.hksvBuilds.lastFor(deviceId), readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? [])),
159548
- readCatalog: async (deviceId) => await this.hksvClipStore?.listCatalog(deviceId) ?? { kind: "no-root" },
159549
- locationRefusal: () => this.hksvClipLocation?.lastRefusal ?? null,
159550
- mediaUrl: (deviceId, stem) => this.hksvClipUrl("media", deviceId, stem),
159551
- thumbnailUrl: (deviceId, stem) => this.hksvClipUrl("thumb", deviceId, stem),
159552
- clipFilePath: async (deviceId, stem) => await this.hksvClipStore?.artifactPath(deviceId, stem, "clip") ?? null
159553
- });
159554
- return [
159555
- {
159556
- capability: deviceExportCapability,
159557
- provider
159558
- },
159559
- {
159560
- capability: videoclipsCapability,
159561
- provider: clipsProvider
159562
- },
159563
- {
159564
- capability: integrationInstancesCapability,
159565
- provider: this.requireInstances().toProvider()
159566
- }
159567
- ];
159568
- }
159569
- async onConfigChanged() {
159570
- const fixedPin = this.config.fixedPin;
159571
- if (!fixedPin || !isValidPincode(fixedPin)) return;
159572
- const handle = this.requireRecords().kind(hapBridgesKind);
159573
- const row = await handle.getResolved(HAP_DEFAULT_INSTANCE_ID);
159574
- if (row === null || row.data.pincode === fixedPin) return;
159575
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode: fixedPin });
159576
159947
  }
159577
159948
  requireInstances() {
159578
159949
  if (this.instances === null) throw new Error("export-hap: instances are not initialised");
@@ -159606,13 +159977,17 @@ var ExportHapAddon = class extends BaseAddon {
159606
159977
  }
159607
159978
  return "created";
159608
159979
  },
159609
- readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null
159980
+ readDefaultRecord: async () => (await handle.getResolved("export-hap"))?.data ?? null,
159981
+ patchDefaultName: async (name) => {
159982
+ await handle.patch(HAP_DEFAULT_INSTANCE_ID, { name });
159983
+ },
159984
+ clearFixedPin: () => this.updateGlobalSettingsAsOperator({ fixedPin: SECRET_CLEAR })
159610
159985
  };
159611
159986
  }
159612
- /** The identity of the default instance; see `resolveBridgeIdentity`. */
159613
- async ensureIdentity() {
159987
+ /** The default bridge: read its record, or mint it on a first boot with no bridge at all. */
159988
+ async ensureDefaultBridge() {
159614
159989
  const handle = this.requireRecords().kind(hapBridgesKind);
159615
- const { identity, minted } = await resolveBridgeIdentity(this.config.fixedPin && isValidPincode(this.config.fixedPin) ? this.config.fixedPin : null, {
159990
+ const boot = await resolveDefaultBridge({
159616
159991
  readRecord: async () => {
159617
159992
  const resolved = await this.requireInstances().readResolved(HAP_DEFAULT_INSTANCE_ID);
159618
159993
  if (resolved === null) return { kind: "absent" };
@@ -159622,9 +159997,7 @@ var ExportHapAddon = class extends BaseAddon {
159622
159997
  } : { kind: "unavailable" };
159623
159998
  },
159624
159999
  legacyIdentityPresent: async () => legacyIdentityOf((await this.resolveGlobalStore())["identity"]) !== null,
159625
- patchPincode: async (pincode) => {
159626
- await handle.patch(HAP_DEFAULT_INSTANCE_ID, { pincode });
159627
- },
160000
+ otherBridgesExist: async () => (await this.requireInstances().listResolved()).some((row) => row.id !== HAP_DEFAULT_INSTANCE_ID),
159628
160001
  putFresh: async (body) => {
159629
160002
  await handle.put({
159630
160003
  id: HAP_DEFAULT_INSTANCE_ID,
@@ -159632,14 +160005,13 @@ var ExportHapAddon = class extends BaseAddon {
159632
160005
  }, { ifRev: 0 });
159633
160006
  },
159634
160007
  mint: () => ({
159635
- name: this.config.bridgeName,
160008
+ name: DEFAULT_BRIDGE_NAME,
159636
160009
  username: generateUsername(),
159637
- uuid: buildBridgeUuid(this.config.bridgeName),
160010
+ uuid: buildBridgeUuid(DEFAULT_BRIDGE_NAME),
159638
160011
  pincode: generatePincode()
159639
160012
  })
159640
160013
  });
159641
- if (minted) this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: identity.username } });
159642
- return identity;
160014
+ if (boot.kind === "minted") this.ctx.logger.info("export-hap: generated bridge identity on first boot", { meta: { username: boot.identity.username } });
159643
160015
  }
159644
160016
  /**
159645
160017
  * Build the generic `device-export` `setup` block surfaced via
@@ -159648,10 +160020,10 @@ var ExportHapAddon = class extends BaseAddon {
159648
160020
  * a copyable field, and a short pairing instruction. Returns `null`
159649
160021
  * until the bridge has booted and produced both values.
159650
160022
  */
159651
- buildSetupBlock() {
159652
- const setupCode = this.pincode;
160023
+ buildSetupBlock(inst) {
160024
+ const setupCode = inst.pincode;
159653
160025
  if (!setupCode) return null;
159654
- const qr = firstExposedAccessorySetupUri(this.exposed, this.ctx.logger);
160026
+ const qr = firstExposedAccessorySetupUri(inst.exposed, this.ctx.logger);
159655
160027
  return {
159656
160028
  ...qr !== void 0 ? { qr } : {},
159657
160029
  fields: [{
@@ -159672,18 +160044,18 @@ var ExportHapAddon = class extends BaseAddon {
159672
160044
  * Measured 2026-09-17 — the stored value read `mid` while the advertisement
159673
160045
  * still said `streamPreference=auto`.
159674
160046
  */
159675
- async exposeDevice(deviceId, capabilities, settings) {
160047
+ async exposeDevice(inst, deviceId, capabilities, settings) {
159676
160048
  const numericId = Number.parseInt(deviceId, 10);
159677
160049
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159678
- if (this.exposed.has(deviceId)) {
160050
+ if (inst.exposed.has(deviceId)) {
159679
160051
  log.debug("export-hap: device already exposed — refreshing capabilities");
159680
- await this.detachMapper(deviceId);
160052
+ await this.detachMapper(inst, deviceId);
159681
160053
  }
159682
160054
  const summary = await this.fetchDeviceSummary(numericId);
159683
160055
  const mapperKind = pickMapperKind(summary?.type);
159684
160056
  if (!mapperKind) throw new Error(`export-hap: device ${numericId} has type '${summary?.type ?? "unknown"}', which HomeKit export does not support`);
159685
160057
  const displayName = summary?.name ?? `Device ${deviceId}`;
159686
- const previous = this.exposure.devices.find((e) => e.deviceId === deviceId);
160058
+ const previous = inst.exposure.devices.find((e) => e.deviceId === deviceId);
159687
160059
  const rebuilt = {
159688
160060
  deviceId,
159689
160061
  displayName,
@@ -159695,37 +160067,38 @@ var ExportHapAddon = class extends BaseAddon {
159695
160067
  ...rebuilt,
159696
160068
  settings
159697
160069
  }, previous, ["settings", "capabilities"]);
159698
- const attached = await this.attachMapper(baseEntry);
160070
+ const attached = await this.attachMapper(inst, baseEntry);
159699
160071
  const finalEntry = {
159700
160072
  ...baseEntry,
159701
160073
  childAccessoryUuids: attached.childAccessoryUuids
159702
160074
  };
159703
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
160075
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
159704
160076
  next.push(finalEntry);
159705
- await this.setExposedDevices(next);
160077
+ await this.setExposedDevices(inst, next);
159706
160078
  if (Number.isFinite(numericId)) {
159707
- const fp = await this.computeExportFingerprint(numericId);
159708
- if (fp !== null) await this.persistFingerprint(numericId, fp);
160079
+ const fp = await this.computeExportFingerprint(inst, numericId);
160080
+ if (fp !== null) await this.persistFingerprint(inst, numericId, fp);
159709
160081
  }
159710
160082
  log.info("export-hap: exposed device", { meta: {
160083
+ instanceId: inst.id,
159711
160084
  displayName,
159712
160085
  mapperKind,
159713
160086
  childCount: attached.childAccessoryUuids.length
159714
160087
  } });
159715
160088
  }
159716
- async unexposeDevice(deviceId, options = {}) {
160089
+ async unexposeDevice(inst, deviceId, options = {}) {
159717
160090
  const numericId = Number.parseInt(deviceId, 10);
159718
160091
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159719
- const mapperKind = this.findEntry(numericId)?.mapperKind ?? "camera";
159720
- await this.detachMapper(deviceId);
159721
- const next = this.exposure.devices.filter((e) => e.deviceId !== deviceId);
159722
- if (next.length !== this.exposure.devices.length) await this.setExposedDevices(next);
159723
- if (options.clearPairing !== false) clearPairingFiles(accessoryUuidFor(mapperKind, numericId), this.ctx.logger);
159724
- await this.forgetFingerprint(numericId);
160092
+ const mapperKind = inst.findEntry(numericId)?.mapperKind ?? "camera";
160093
+ await this.detachMapper(inst, deviceId);
160094
+ const next = inst.exposure.devices.filter((e) => e.deviceId !== deviceId);
160095
+ if (next.length !== inst.exposure.devices.length) await this.setExposedDevices(inst, next);
160096
+ if (options.clearPairing !== false) clearPairingFiles(inst.accessoryUuidOf(mapperKind, numericId), this.ctx.logger);
160097
+ await this.forgetFingerprint(inst, numericId);
159725
160098
  this.hksvBuilds.forget(numericId);
159726
- log.info("export-hap: unexposed device");
160099
+ log.info("export-hap: unexposed device", { meta: { instanceId: inst.id } });
159727
160100
  }
159728
- async attachMapper(entry) {
160101
+ async attachMapper(inst, entry) {
159729
160102
  const factory = getMapperFactory(entry.mapperKind);
159730
160103
  const entrySettings = entry.settings ?? DEFAULT_DEVICE_SETTINGS;
159731
160104
  const mapper = await factory({
@@ -159733,6 +160106,7 @@ var ExportHapAddon = class extends BaseAddon {
159733
160106
  deviceId: entry.deviceId,
159734
160107
  displayName: entry.displayName,
159735
160108
  options: {
160109
+ instanceId: inst.id,
159736
160110
  decodeMemos: this.decodeMemos,
159737
160111
  resolveFfmpeg: this.pinnedFfmpeg,
159738
160112
  hksvClipStore: this.hksvClipStore,
@@ -159752,29 +160126,29 @@ var ExportHapAddon = class extends BaseAddon {
159752
160126
  useBridge: entry.settings?.useBridge
159753
160127
  });
159754
160128
  for (const accessory of mapper.accessories) {
159755
- if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
160129
+ if (wantsBridge && await inst.bridgeHost.add(accessory)) continue;
159756
160130
  await publishStandalone(accessory, {
159757
- pincode: this.pincode,
160131
+ pincode: inst.pincode,
159758
160132
  port: 0,
159759
160133
  bind: this.bind,
159760
160134
  logger: this.ctx.logger
159761
160135
  });
159762
160136
  }
159763
- this.exposed.set(entry.deviceId, mapper);
160137
+ inst.exposed.set(entry.deviceId, mapper);
159764
160138
  return { childAccessoryUuids: [] };
159765
160139
  }
159766
- async detachMapper(deviceId) {
159767
- const pendingTimer = this.pendingRebuildTimers.get(deviceId);
160140
+ async detachMapper(inst, deviceId) {
160141
+ const pendingTimer = inst.pendingRebuildTimers.get(deviceId);
159768
160142
  if (pendingTimer) {
159769
160143
  clearTimeout(pendingTimer);
159770
- this.pendingRebuildTimers.delete(deviceId);
160144
+ inst.pendingRebuildTimers.delete(deviceId);
159771
160145
  }
159772
- const mapper = this.exposed.get(deviceId);
160146
+ const mapper = inst.exposed.get(deviceId);
159773
160147
  if (!mapper) return;
159774
- this.exposed.delete(deviceId);
160148
+ inst.exposed.delete(deviceId);
159775
160149
  for (const accessory of mapper.accessories) {
159776
- if (this.bridgeHost?.holds(accessory) === true) {
159777
- this.bridgeHost.remove(accessory);
160150
+ if (inst.bridgeHost.holds(accessory)) {
160151
+ inst.bridgeHost.remove(accessory);
159778
160152
  continue;
159779
160153
  }
159780
160154
  await unpublishAccessory(accessory, this.ctx.logger);
@@ -159783,21 +160157,22 @@ var ExportHapAddon = class extends BaseAddon {
159783
160157
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
159784
160158
  });
159785
160159
  }
159786
- requireActionExports() {
159787
- if (this.actionExports === null) throw new Error("export-hap: addon is not initialised");
159788
- return this.actionExports;
160160
+ requireActionExports(inst) {
160161
+ if (inst.actionExports === null) throw new Error("export-hap: bridge is not initialised");
160162
+ return inst.actionExports;
159789
160163
  }
159790
- async detachAll() {
159791
- const ids = Array.from(this.exposed.keys());
159792
- for (const id of ids) await this.detachMapper(id);
160164
+ async detachAll(inst) {
160165
+ const ids = Array.from(inst.exposed.keys());
160166
+ for (const id of ids) await this.detachMapper(inst, id);
159793
160167
  }
159794
- /** Pending rebuild timers per deviceId — used to debounce. Cleared
159795
- * on detach so stale timers can't republish a removed accessory. */
159796
- pendingRebuildTimers = /* @__PURE__ */ new Map();
159797
160168
  /** Deterministic HAP accessory UUID for a device — the same one the
159798
160169
  * orchestrator built it with (`mappers/kind.ts`). */
159799
- hapAccessoryUuid(deviceId) {
159800
- return accessoryUuidFor(this.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160170
+ hapAccessoryUuid(inst, deviceId) {
160171
+ return inst.accessoryUuidOf(inst.findEntry(deviceId)?.mapperKind ?? "camera", deviceId);
160172
+ }
160173
+ /** The reconcile cache of a bridge: the default one is persisted, the others live in memory (boot re-attach seeds them). */
160174
+ syncStateOf(inst) {
160175
+ return inst.id === "export-hap" ? syncStateFromJson(this.config.exportSyncState) : inst.syncState;
159801
160176
  }
159802
160177
  /**
159803
160178
  * Export fingerprint of a device from its PERSISTED features + type
@@ -159815,7 +160190,7 @@ var ExportHapAddon = class extends BaseAddon {
159815
160190
  * A brand-new un-probed device with no persisted entry falls back to its
159816
160191
  * fresh fingerprint (publishes once, acceptable).
159817
160192
  */
159818
- async computeExportFingerprint(deviceId) {
160193
+ async computeExportFingerprint(inst, deviceId) {
159819
160194
  try {
159820
160195
  const device = await this.ctx.api.deviceManager.getDevice.query({ deviceId });
159821
160196
  if (!device) return null;
@@ -159824,10 +160199,10 @@ var ExportHapAddon = class extends BaseAddon {
159824
160199
  deviceType: device.type,
159825
160200
  features: device.features
159826
160201
  });
159827
- const persisted = syncStateFromJson(this.config.exportSyncState).get(deviceId)?.fingerprint;
160202
+ const persisted = this.syncStateOf(inst).get(deviceId)?.fingerprint;
159828
160203
  const withToken = withRecordabilityToken({
159829
160204
  base: fresh,
159830
- token: await this.readRecordabilityToken(deviceId, device.type),
160205
+ token: await this.readRecordabilityToken(inst, deviceId, device.type),
159831
160206
  persisted
159832
160207
  });
159833
160208
  return resolveExportFingerprint({
@@ -159847,12 +160222,12 @@ var ExportHapAddon = class extends BaseAddon {
159847
160222
  * republish every non-camera accessory once for nothing) and for a camera
159848
160223
  * whose profiles could not be read right now.
159849
160224
  */
159850
- async readRecordabilityToken(deviceId, type) {
160225
+ async readRecordabilityToken(inst, deviceId, type) {
159851
160226
  if (pickMapperKind(type) !== "camera") return null;
159852
160227
  try {
159853
160228
  const entries = await (await this.ctx.fetchDevice(deviceId)).cameraStreams?.getProfileRtspEntries({});
159854
160229
  return recordabilityTokenFor({
159855
- allowTranscode: this.findEntry(deviceId)?.settings?.allowTranscode !== false,
160230
+ allowTranscode: inst.findEntry(deviceId)?.settings?.allowTranscode !== false,
159856
160231
  entries: entries ?? null
159857
160232
  });
159858
160233
  } catch {
@@ -159861,20 +160236,20 @@ var ExportHapAddon = class extends BaseAddon {
159861
160236
  }
159862
160237
  /** Persist a device's current export fingerprint into `exportSyncState`
159863
160238
  * (best-effort; called after a successful attach). */
159864
- async persistFingerprint(deviceId, fingerprint) {
159865
- const state = syncStateFromJson(this.config.exportSyncState);
160239
+ async persistFingerprint(inst, deviceId, fingerprint) {
160240
+ const state = this.syncStateOf(inst);
159866
160241
  state.set(deviceId, {
159867
160242
  fingerprint,
159868
- externalIds: [this.hapAccessoryUuid(deviceId)]
160243
+ externalIds: [this.hapAccessoryUuid(inst, deviceId)]
159869
160244
  });
159870
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160245
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159871
160246
  }
159872
160247
  /** Drop a device's `exportSyncState` entry (on unexpose). */
159873
- async forgetFingerprint(deviceId) {
159874
- const state = syncStateFromJson(this.config.exportSyncState);
160248
+ async forgetFingerprint(inst, deviceId) {
160249
+ const state = this.syncStateOf(inst);
159875
160250
  if (!state.has(deviceId)) return;
159876
160251
  state.delete(deviceId);
159877
- await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
160252
+ if (inst.id === "export-hap") await this.updateGlobalSettings({ exportSyncState: syncStateToJson(state) });
159878
160253
  }
159879
160254
  /**
159880
160255
  * Subscribe to a device-lifecycle event category and reconcile the exposed
@@ -159905,34 +160280,23 @@ var ExportHapAddon = class extends BaseAddon {
159905
160280
  const deviceIdNumeric = typeof data?.deviceId === "number" ? data.deviceId : null;
159906
160281
  if (deviceIdNumeric === null) return;
159907
160282
  const deviceId = String(deviceIdNumeric);
159908
- if (!this.findEntry(deviceIdNumeric)) return;
159909
- const existing = this.pendingRebuildTimers.get(deviceId);
159910
- if (existing) clearTimeout(existing);
159911
- const timer = setTimeout(() => {
159912
- this.pendingRebuildTimers.delete(deviceId);
159913
- this.reconcileDevice(deviceId);
159914
- }, 500);
159915
- if (typeof timer.unref === "function") timer.unref();
159916
- this.pendingRebuildTimers.set(deviceId, timer);
160283
+ for (const inst of this.bridges.values()) {
160284
+ if (!inst.findEntry(deviceIdNumeric)) continue;
160285
+ const existing = inst.pendingRebuildTimers.get(deviceId);
160286
+ if (existing) clearTimeout(existing);
160287
+ const timer = setTimeout(() => {
160288
+ inst.pendingRebuildTimers.delete(deviceId);
160289
+ this.reconcileDevice(inst, deviceId);
160290
+ }, 500);
160291
+ if (typeof timer.unref === "function") timer.unref();
160292
+ inst.pendingRebuildTimers.set(deviceId, timer);
160293
+ }
159917
160294
  });
159918
160295
  this.ctx.addDisposer(async () => {
159919
160296
  unsubscribe();
159920
160297
  });
159921
160298
  }
159922
160299
  /**
159923
- * Register the SINGLE owner of the shared rebuild-timer cleanup. Called once
159924
- * from `onInitialize`. The per-category lifecycle subscriptions schedule
159925
- * per-device timers into `pendingRebuildTimers` but never clear the map on
159926
- * their own teardown — that shared resource is cleared here, exactly once, on
159927
- * shutdown.
159928
- */
159929
- disposeSharedRebuildTimers() {
159930
- this.ctx.addDisposer(async () => {
159931
- for (const timer of this.pendingRebuildTimers.values()) clearTimeout(timer);
159932
- this.pendingRebuildTimers.clear();
159933
- });
159934
- }
159935
- /**
159936
160300
  * Subscribe to `DeviceProvisioned` and reconcile an exposed device whenever
159937
160301
  * its persisted export shape changes. `DeviceProvisioned` is gated by
159938
160302
  * device-manager (fires ONLY on first registration or a real fingerprint
@@ -159962,22 +160326,22 @@ var ExportHapAddon = class extends BaseAddon {
159962
160326
  * Errors are logged and swallowed — a failed reconcile leaves the prior
159963
160327
  * accessory up, which is strictly better than removing it.
159964
160328
  */
159965
- async reconcileDevice(deviceId) {
160329
+ async reconcileDevice(inst, deviceId) {
159966
160330
  const numericId = Number.parseInt(deviceId, 10);
159967
160331
  if (!Number.isFinite(numericId)) return;
159968
- const entry = this.findEntry(numericId);
160332
+ const entry = inst.findEntry(numericId);
159969
160333
  if (!entry) return;
159970
160334
  const log = this.ctx.logger.withTags({ deviceId: numericId });
159971
- const current = await this.computeExportFingerprint(numericId);
160335
+ const current = await this.computeExportFingerprint(inst, numericId);
159972
160336
  if (current === null) {
159973
160337
  log.debug("export-hap: reconcile skipped — fingerprint unavailable (transient)");
159974
160338
  return;
159975
160339
  }
159976
- const last = syncStateFromJson(this.config.exportSyncState).get(numericId);
160340
+ const last = this.syncStateOf(inst).get(numericId);
159977
160341
  if (last?.fingerprint === current) {
159978
- if (!this.exposed.has(deviceId)) try {
159979
- await this.attachMapper(entry);
159980
- await this.persistFingerprint(numericId, current);
160342
+ if (!inst.exposed.has(deviceId)) try {
160343
+ await this.attachMapper(inst, entry);
160344
+ await this.persistFingerprint(inst, numericId, current);
159981
160345
  } catch (err) {
159982
160346
  log.warn("export-hap: reconcile attach failed", { meta: { error: errMsg(err) } });
159983
160347
  }
@@ -159989,9 +160353,9 @@ var ExportHapAddon = class extends BaseAddon {
159989
160353
  to: current.slice(0, 12)
159990
160354
  } });
159991
160355
  try {
159992
- await this.detachMapper(deviceId);
159993
- await this.attachMapper(entry);
159994
- await this.persistFingerprint(numericId, current);
160356
+ await this.detachMapper(inst, deviceId);
160357
+ await this.attachMapper(inst, entry);
160358
+ await this.persistFingerprint(inst, numericId, current);
159995
160359
  } catch (err) {
159996
160360
  log.warn("export-hap: reconcile rebuild failed", { meta: { error: errMsg(err) } });
159997
160361
  }
@@ -160054,7 +160418,7 @@ var ExportHapAddon = class extends BaseAddon {
160054
160418
  return null;
160055
160419
  }
160056
160420
  }
160057
- /** The one declaration of the bind-interface field, shared by the node form and the global form. */
160421
+ /** The one declaration of the bind-interface field: a fact of one node. */
160058
160422
  interfaceNameField() {
160059
160423
  return this.field({
160060
160424
  type: "text",
@@ -160074,10 +160438,26 @@ var ExportHapAddon = class extends BaseAddon {
160074
160438
  fields: [this.interfaceNameField()]
160075
160439
  }] }) : null;
160076
160440
  }
160441
+ /** The fleet default every camera's clip retention cascades from (same key, no data move). */
160442
+ async deviceDefaultsSchema(cap) {
160443
+ return cap === "device-export" ? this.schema({ sections: [{
160444
+ id: "export-hap-defaults",
160445
+ title: "HomeKit Export",
160446
+ fields: [this.field({
160447
+ type: "number",
160448
+ key: "clipRetentionDays",
160449
+ label: "Keep HomeKit clips for (days)",
160450
+ 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.",
160451
+ default: DEFAULT_CONFIG.clipRetentionDays,
160452
+ placement: { tab: "advanced" }
160453
+ })]
160454
+ }] }) : null;
160455
+ }
160077
160456
  /**
160078
- * Copy the bare `interfaceName` to its hub node row and move an inline `fixedPin` into the
160079
- * keychain (D986, D987). Re-resolves the config when either landed, so this boot binds the
160080
- * value the migration wrote.
160457
+ * Move the old settings to where they live now (D986, D987): the bare `interfaceName` to its
160458
+ * node row, the identity and exposure into records, the bridge name into the default instance,
160459
+ * and the retired `bridgeName` / `fixedPin` / bare `interfaceName` rows out. Re-resolves the
160460
+ * config when anything landed, so this boot binds the value the migration wrote.
160081
160461
  */
160082
160462
  async migrateSettings() {
160083
160463
  if ((await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
@@ -160087,47 +160467,24 @@ var ExportHapAddon = class extends BaseAddon {
160087
160467
  ...this.exposureMigrationPorts()
160088
160468
  }))).applied.length > 0) await this.resolveConfig();
160089
160469
  }
160470
+ /**
160471
+ * Only the declaration `perNodeKeys()` derives the node-scoped keys from: `interfaceName` is a
160472
+ * fact of one node, and the settings machinery reads a per-node key through this schema. The
160473
+ * editable surfaces are the node form, the device defaults and each bridge's own form.
160474
+ */
160090
160475
  globalSettingsSchema() {
160091
160476
  return this.schema({ sections: [{
160092
160477
  id: "export-hap",
160093
160478
  title: "HomeKit Export",
160094
- description: "Publishes each exposed device as its own HomeKit accessory, sharing one setup code. Mark a device \"Expose to HomeKit\" on its settings page, then add it in the iOS Home app (+ → Add Accessory) and enter the setup code shown there.",
160095
- columns: 1,
160096
- fields: [
160097
- this.field({
160098
- type: "text",
160099
- key: "bridgeName",
160100
- label: "Installation name",
160101
- description: "The name of the shared bridge that carries every exposed device that is not a camera (switches, sensors, locks, alarm panels) — what iOS Home lists under Add Accessory. Cameras are never bridged: each one is published as its own accessory under its device name. Set it before you add the bridge in iOS Home.",
160102
- default: DEFAULT_CONFIG.bridgeName,
160103
- requiresRestart: true,
160104
- placement: { tab: "advanced" }
160105
- }),
160106
- this.field({
160107
- type: "password",
160108
- key: "fixedPin",
160109
- label: "Fixed setup code (XXX-XX-XXX)",
160110
- description: "Optional. Leave blank to use the auto-generated code persisted on first boot. Useful for CI replay.",
160111
- default: DEFAULT_CONFIG.fixedPin,
160112
- requiresRestart: true,
160113
- placement: { tab: "advanced" }
160114
- }),
160115
- this.interfaceNameField(),
160116
- this.field({
160117
- type: "number",
160118
- key: "clipRetentionDays",
160119
- label: "Keep HomeKit clips for (days)",
160120
- description: "CamStack keeps its own copy of every clip it sends to HomeKit Secure Video — HomeKit itself never gives one back. This is the fleet default; each camera can override it, and each can switch the copies off entirely. Clips are also capped at 200 per camera, 512 MB per camera and 4 GB overall — whichever limit is reached first wins, and the log names which one.",
160121
- default: DEFAULT_CONFIG.clipRetentionDays,
160122
- placement: { tab: "advanced" }
160123
- })
160124
- ]
160479
+ fields: [this.interfaceNameField()]
160125
160480
  }] });
160126
160481
  }
160127
160482
  async buildDeviceSettingsContribution(deviceId) {
160128
160483
  const kind = await this.resolveExportKind(deviceId);
160129
160484
  if (kind === null) return null;
160130
- const entry = this.findEntry(deviceId);
160485
+ const inst = this.instanceForDevice(deviceId);
160486
+ if (inst === null) return null;
160487
+ const entry = inst.findEntry(deviceId);
160131
160488
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
160132
160489
  const enabled = entry !== null;
160133
160490
  const enabledKey = `hap:${deviceId}:enabled`;
@@ -160137,13 +160494,13 @@ var ExportHapAddon = class extends BaseAddon {
160137
160494
  const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
160138
160495
  const keepClipsKey = `hap:${deviceId}:keepClips`;
160139
160496
  const clipRetentionKey = `hap:${deviceId}:clipRetentionDays`;
160140
- const mapper = this.exposed.get(String(deviceId)) ?? null;
160497
+ const mapper = inst.exposed.get(String(deviceId)) ?? null;
160141
160498
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
160142
- const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
160499
+ const bridged = mapper !== null && inst.bridgeHost.holds(mapper.accessory);
160143
160500
  const name = entry?.displayName ?? `Device ${deviceId}`;
160144
- const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
160145
- const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.pincode}.`;
160146
- const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
160501
+ const bridgePaired = inst.bridgeHost.accessory !== null ? accessoryPaired(inst.bridgeHost.accessory) : false;
160502
+ 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}.`;
160503
+ const qrSource = bridged ? inst.bridgeHost.accessory : mapper?.accessory ?? null;
160147
160504
  let qrValue = "";
160148
160505
  if (qrSource) try {
160149
160506
  qrValue = qrSource.setupURI();
@@ -160185,7 +160542,7 @@ var ExportHapAddon = class extends BaseAddon {
160185
160542
  type: "info",
160186
160543
  key: `hap:${deviceId}:hksvRecordingStatus`,
160187
160544
  label: "HomeKit recording (Secure Video)",
160188
- content: describeHomekitRecording(readHomekitRecordingActive(this.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160545
+ content: describeHomekitRecording(readHomekitRecordingActive(inst.exposed.get(String(deviceId))?.accessories ?? []), this.hksvBuilds.lastFor(deviceId)),
160189
160546
  showWhen: {
160190
160547
  field: enabledKey,
160191
160548
  equals: true
@@ -160269,7 +160626,7 @@ var ExportHapAddon = class extends BaseAddon {
160269
160626
  type: "qr-code",
160270
160627
  key: "__hap-pair-qr",
160271
160628
  label: paired ? "Pairing QR (already paired)" : "Pairing QR",
160272
- caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${this.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${this.pincode}.`,
160629
+ caption: paired ? `Already paired with at least one device. Scan from another iPhone / iPad to add it there too. Setup code: ${inst.pincode}.` : `Scan with the iOS Camera app to pair this accessory in HomeKit. Setup code: ${inst.pincode}.`,
160273
160630
  value: qrValue,
160274
160631
  size: 192,
160275
160632
  alt: `HomeKit pairing QR for ${name}`,
@@ -160308,8 +160665,10 @@ var ExportHapAddon = class extends BaseAddon {
160308
160665
  async applyDeviceSettingsPatch(deviceId, patch) {
160309
160666
  const deviceIdStr = String(deviceId);
160310
160667
  const log = this.ctx.logger.withTags({ deviceId });
160311
- const current = this.findEntry(deviceId);
160312
- const wasEnabled = this.exposed.has(deviceIdStr);
160668
+ const inst = this.instanceForDevice(deviceId);
160669
+ if (inst === null) throw new Error("export-hap: no HomeKit bridge is running — add or enable one first");
160670
+ const current = inst.findEntry(deviceId);
160671
+ const wasEnabled = inst.exposed.has(deviceIdStr);
160313
160672
  const enabledKey = `hap:${deviceId}:enabled`;
160314
160673
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
160315
160674
  const useBridgeKey = `hap:${deviceId}:useBridge`;
@@ -160338,12 +160697,12 @@ var ExportHapAddon = class extends BaseAddon {
160338
160697
  clipRetentionDays
160339
160698
  };
160340
160699
  if (!enabledValue) {
160341
- if (wasEnabled) await this.unexposeDevice(deviceIdStr);
160700
+ if (wasEnabled) await this.unexposeDevice(inst, deviceIdStr);
160342
160701
  return { success: true };
160343
160702
  }
160344
160703
  if (!wasEnabled) {
160345
- await this.exposeDevice(deviceIdStr);
160346
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160704
+ await this.exposeDevice(inst, deviceIdStr);
160705
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160347
160706
  return { success: true };
160348
160707
  }
160349
160708
  const currentPref = current?.settings?.streamPreference ?? "auto";
@@ -160357,7 +160716,7 @@ var ExportHapAddon = class extends BaseAddon {
160357
160716
  mapperKind,
160358
160717
  useBridge
160359
160718
  });
160360
- await this.updateEntrySettings(deviceIdStr, nextSettings);
160719
+ await this.updateEntrySettings(inst, deviceIdStr, nextSettings);
160361
160720
  if (currentPref !== streamPreference || currentKeepClips !== keepClips || wasBridged !== willBridge) {
160362
160721
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
160363
160722
  streamPreference: {
@@ -160374,8 +160733,8 @@ var ExportHapAddon = class extends BaseAddon {
160374
160733
  }
160375
160734
  } });
160376
160735
  try {
160377
- await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
160378
- await this.exposeDevice(deviceIdStr, void 0, nextSettings);
160736
+ await this.unexposeDevice(inst, deviceIdStr, { clearPairing: wasBridged !== willBridge });
160737
+ await this.exposeDevice(inst, deviceIdStr, void 0, nextSettings);
160379
160738
  } catch (err) {
160380
160739
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
160381
160740
  }
@@ -160437,35 +160796,38 @@ var ExportHapAddon = class extends BaseAddon {
160437
160796
  exposureHandle() {
160438
160797
  return this.requireRecords().kind(hapBridgeExportsKind);
160439
160798
  }
160440
- /** Load the default instance's exposure record; create it empty when none exists. */
160441
- async loadExposure() {
160799
+ /** Load a bridge's exposure record; create it empty when none exists. */
160800
+ async loadExposure(id) {
160442
160801
  const handle = this.exposureHandle();
160443
- const row = await handle.get(HAP_DEFAULT_INSTANCE_ID);
160444
- if (row !== null) {
160445
- this.exposure = row.data;
160446
- return;
160447
- }
160802
+ const row = await handle.get(id);
160803
+ if (row !== null) return row.data;
160804
+ const empty = {
160805
+ name: HAP_EXPOSURE_NAME,
160806
+ devices: [],
160807
+ actions: []
160808
+ };
160448
160809
  await handle.put({
160449
- id: HAP_DEFAULT_INSTANCE_ID,
160450
- data: this.exposure
160810
+ id,
160811
+ data: empty
160451
160812
  }, { ifRev: 0 });
160813
+ return empty;
160452
160814
  }
160453
- async writeExposure(next) {
160815
+ async writeExposure(inst, next) {
160454
160816
  await this.exposureHandle().put({
160455
- id: HAP_DEFAULT_INSTANCE_ID,
160817
+ id: inst.id,
160456
160818
  data: next
160457
160819
  });
160458
- this.exposure = next;
160820
+ inst.exposure = next;
160459
160821
  }
160460
- setExposedDevices(devices) {
160461
- return this.writeExposure({
160462
- ...this.exposure,
160822
+ setExposedDevices(inst, devices) {
160823
+ return this.writeExposure(inst, {
160824
+ ...inst.exposure,
160463
160825
  devices
160464
160826
  });
160465
160827
  }
160466
- setExposedActions(actions) {
160467
- return this.writeExposure({
160468
- ...this.exposure,
160828
+ setExposedActions(inst, actions) {
160829
+ return this.writeExposure(inst, {
160830
+ ...inst.exposure,
160469
160831
  actions
160470
160832
  });
160471
160833
  }
@@ -160489,20 +160851,16 @@ var ExportHapAddon = class extends BaseAddon {
160489
160851
  readExposure: async () => (await handle.get("export-hap"))?.data ?? null
160490
160852
  };
160491
160853
  }
160492
- findEntry(deviceId) {
160493
- const id = String(deviceId);
160494
- return this.exposure.devices.find((e) => e.deviceId === id) ?? null;
160495
- }
160496
- async updateEntrySettings(deviceIdStr, settings) {
160497
- const next = this.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160854
+ async updateEntrySettings(inst, deviceIdStr, settings) {
160855
+ const next = inst.exposure.devices.map((e) => e.deviceId === deviceIdStr ? {
160498
160856
  ...e,
160499
160857
  settings
160500
160858
  } : e);
160501
- await this.setExposedDevices(next);
160859
+ await this.setExposedDevices(inst, next);
160502
160860
  }
160503
160861
  };
160504
160862
  function errMsg(err) {
160505
160863
  return err instanceof Error ? err.message : String(err);
160506
160864
  }
160507
160865
  //#endregion
160508
- export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };
160866
+ export { DEFAULT_CLIP_RETENTION_DAYS, DEFAULT_DEVICE_SETTINGS, EXPORT_HAP_ADDON_ID, ExportHapAddon, ExportHapAddon as default, exportHapActions as a, describeHksvCamera, unpublishAccessory as i, initHapStorage as n, publishStandalone as r, resolveClipRetentionDays, resolveKeepHomekitClips, resolveMultiTierService, deriveUsername as t };