@mega-yfue/eufy-sdk 0.5.0-beta.4 → 0.5.0-beta.40

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.
Files changed (40) hide show
  1. package/dist/client/device-registry.d.ts +24 -2
  2. package/dist/client/eufy-mega.d.ts +50 -6
  3. package/dist/client/types.d.ts +1 -1
  4. package/dist/core/contracts.d.ts +52 -26
  5. package/dist/core/store.d.ts +2 -0
  6. package/dist/core/types.d.ts +2 -0
  7. package/dist/index.js +2308 -277
  8. package/dist/index.js.map +4 -4
  9. package/dist/model/capabilities/arming.d.ts +31 -4
  10. package/dist/model/capabilities/camera.d.ts +24 -10
  11. package/dist/model/capabilities/dp-catalog.d.ts +4 -3
  12. package/dist/model/capabilities/light.d.ts +3 -0
  13. package/dist/model/capabilities/motion.d.ts +5 -0
  14. package/dist/model/capabilities/suction.d.ts +5 -5
  15. package/dist/model/capabilities/types.d.ts +6 -0
  16. package/dist/model/capabilities/vacuum-clean.d.ts +19 -13
  17. package/dist/model/classify.d.ts +1 -2
  18. package/dist/model/device-family.d.ts +4 -0
  19. package/dist/model/registry.d.ts +3 -2
  20. package/dist/model/types.d.ts +6 -0
  21. package/dist/transport/abortable.d.ts +8 -0
  22. package/dist/transport/http/mega-client.d.ts +26 -0
  23. package/dist/transport/p2p/command-router.d.ts +14 -26
  24. package/dist/transport/p2p/fmp4.d.ts +12 -2
  25. package/dist/transport/p2p/live-stream.d.ts +3 -0
  26. package/dist/transport/p2p/p2p-session.d.ts +23 -3
  27. package/dist/transport/p2p/recording-download.d.ts +4 -3
  28. package/dist/transport/p2p/shared-live-source.d.ts +9 -0
  29. package/dist/transport/p2p/talkback.d.ts +21 -10
  30. package/dist/transport/p2p/video.d.ts +5 -2
  31. package/dist/transport/rtc/command-router.d.ts +109 -0
  32. package/dist/transport/rtc/live.d.ts +69 -0
  33. package/dist/transport/rtc/peer.d.ts +101 -0
  34. package/dist/transport/rtc/portal-packet.d.ts +72 -0
  35. package/dist/transport/rtc/ptcs-framer.d.ts +86 -0
  36. package/dist/transport/rtc/scall-sdp.d.ts +42 -0
  37. package/dist/transport/rtc/session.d.ts +88 -0
  38. package/dist/transport/rtc/signaling.d.ts +139 -0
  39. package/dist/transport/token-echo.d.ts +8 -0
  40. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var __export = (target, all) => {
5
5
  };
6
6
 
7
7
  // dist/client/eufy-mega.js
8
- import { EventEmitter as EventEmitter9 } from "node:events";
8
+ import { EventEmitter as EventEmitter13 } from "node:events";
9
9
 
10
10
  // dist/transport/http/mega-client.js
11
11
  import { createHash as createHash3 } from "node:crypto";
@@ -196,6 +196,11 @@ var ConsoleLogger = class {
196
196
  }
197
197
  };
198
198
 
199
+ // dist/transport/token-echo.js
200
+ function withoutTokenEcho(text2) {
201
+ return text2.replace(/token\s*[=:]\s*"?[A-Za-z0-9._-]{8,}"?/gi, "token = <redacted>");
202
+ }
203
+
199
204
  // dist/transport/http/media-download.js
200
205
  import { lookup } from "node:dns/promises";
201
206
  import { BlockList, isIP } from "node:net";
@@ -1557,12 +1562,11 @@ var CONTENDED_SESSION_HINT = "the token was rejected again soon after it was las
1557
1562
  function tokenRejected(code, msg) {
1558
1563
  return code === EufyCloudErrorCode.SESSION_KICKED || /user_id is empty|invalid[^,]*\btoken\b|\btoken\b[^,]*(expired|error|not exist)|kicked|(?:\btoken\b|\bsession\b)[^,]*does not exist|unauthor/i.test(msg ?? "");
1559
1564
  }
1560
- function withoutTokenEcho(text2) {
1561
- return text2.replace(/token\s*[=:]\s*"?[A-Za-z0-9._-]{8,}"?/gi, "token = <redacted>");
1562
- }
1563
1565
  var MegaHttpClient = class {
1564
1566
  cfg;
1565
1567
  region;
1568
+ /** The host `estimate_domain` answered, persisted with the session. */
1569
+ estimatedDomain = "";
1566
1570
  bootstrapDomain;
1567
1571
  sessionKey;
1568
1572
  /** Per-host ECDH session keys for non-mega gateways (e.g. eufylife) keyed by host. */
@@ -1643,6 +1647,7 @@ var MegaHttpClient = class {
1643
1647
  if (!isSessionValid(saved) || !saved)
1644
1648
  return void 0;
1645
1649
  this.region = saved.region;
1650
+ this.estimatedDomain = saved.estimatedDomain ?? "";
1646
1651
  this.auth_ = {
1647
1652
  userId: saved.userId,
1648
1653
  accountUserId: saved.accountUserId,
@@ -1667,6 +1672,24 @@ var MegaHttpClient = class {
1667
1672
  get regionShard() {
1668
1673
  return this.region;
1669
1674
  }
1675
+ /**
1676
+ * The shard the RTC signalling signs on: the regional prefix of the estimated domain
1677
+ * (`…-ie-…`/`…-ie.` → `ie-pr`), else {@link regionShard}. The eu/us classification cannot name shards
1678
+ * like `ie-pr`, whose accounts need the IE sign host and cluster.
1679
+ */
1680
+ get rtcShard() {
1681
+ const m = /-([a-z]{2})(?:[.-]|$)/i.exec(this.estimatedDomain);
1682
+ return m ? `${m[1].toLowerCase()}-pr` : this.region;
1683
+ }
1684
+ /**
1685
+ * The credentials the RTC signalling needs; `undefined` while logged out. The sign is refused
1686
+ * ("gtoken not equal userid") unless its gtoken is the one every authed HTTP call carries.
1687
+ */
1688
+ rtcIdentity() {
1689
+ if (!this.auth_)
1690
+ return void 0;
1691
+ return { authToken: this.auth_.authToken, userId: this.auth_.userId, gtoken: gtoken(this.gtokenUserId()) };
1692
+ }
1670
1693
  /**
1671
1694
  * The name commands attribute themselves to — {@link MegaClientConfig.accountName} when the config
1672
1695
  * pins one (trimmed; blank counts as unset), otherwise the logged-in account's display name, which
@@ -1764,6 +1787,7 @@ var MegaHttpClient = class {
1764
1787
  const env = res.data;
1765
1788
  const d = env?.data ?? {};
1766
1789
  const domain = d.domain ?? d.host ?? d.server_secret_info ?? "";
1790
+ this.estimatedDomain = domain;
1767
1791
  const blob = JSON.stringify(d);
1768
1792
  if (blob.includes("-eu-") || domain.includes("-eu-"))
1769
1793
  this.region = "eu-pr";
@@ -1974,6 +1998,17 @@ ${this.auth_?.authToken ?? ""}`;
1974
1998
  device_sns: [deviceSn]
1975
1999
  });
1976
2000
  }
2001
+ /**
2002
+ * Fetch the account's devices as the `devicerelation` service lists them, `{attribute: 7, house_id: ""}`.
2003
+ *
2004
+ * Each entry is `{device: {device_sn, dps, …}}`, and `dps` is the cloud's last-known value of every
2005
+ * data point that device has reported, keyed by DP number. Answered for an account a device is shared
2006
+ * with as well as for its owner. Sent with `category: eufy_home`, without which the service answers
2007
+ * `10000`.
2008
+ */
2009
+ getDeviceRelationList() {
2010
+ return this.post("devicerelation", "/app/devicerelation/get_device_list", { attribute: 7, house_id: "" }, { category: "eufy_home" });
2011
+ }
1977
2012
  /**
1978
2013
  * Fetch one page of a device's **cleaning history** from the mega `clean` service.
1979
2014
  *
@@ -2422,6 +2457,7 @@ ${this.auth_?.authToken ?? ""}`;
2422
2457
  authToken: this.auth_.authToken,
2423
2458
  geoKey: this.auth_.geoKey,
2424
2459
  region: this.region,
2460
+ estimatedDomain: this.estimatedDomain,
2425
2461
  openudid: this.openudid,
2426
2462
  phoneModel: this.phoneModel,
2427
2463
  mediaUserAgent: this.mediaUserAgent,
@@ -3034,8 +3070,7 @@ var STATION_TYPES = /* @__PURE__ */ new Set([
3034
3070
  DeviceType.STATION_9000,
3035
3071
  DeviceType.MINIBASE_CHIME,
3036
3072
  DeviceType.HOMEBASE_MINI,
3037
- DeviceType.NVR_S4_MAX,
3038
- DeviceType.CAMERA_POE_S4
3073
+ DeviceType.NVR_S4_MAX
3039
3074
  ]);
3040
3075
  var LOCK_TYPES = /* @__PURE__ */ new Set([
3041
3076
  DeviceType.LOCK_BLE,
@@ -3109,7 +3144,7 @@ function codecFromModel(model) {
3109
3144
  return "vacuum";
3110
3145
  if (/^T8(00[0-9]|010|023|025|030)/.test(m))
3111
3146
  return "station";
3112
- if (/^T8N0/.test(m) || /^T8E0/.test(m))
3147
+ if (/^T8N0/.test(m))
3113
3148
  return "station";
3114
3149
  if (/^T9000/.test(m))
3115
3150
  return "station";
@@ -4219,6 +4254,10 @@ var MOTION_MEMBERS = {
4219
4254
  * The raw sensitivity an indoor camera reports, on the one id whose write takes a `1700` control
4220
4255
  * payload carrying an index rather than the `1350` envelope its siblings use — a frame-shape
4221
4256
  * difference `sensitivityCommand` resolves from the scale. `unexposed` like its three siblings.
4257
+ *
4258
+ * Some devices report 6041 as a base64 JSON list of per-sensor entries
4259
+ * (`{"list":[{"sensor_id":…,"sensitivity":…}]}`) rather than a scalar. That value is stored verbatim
4260
+ * and this getter answers `undefined` for it: only the scalar form is confirmed to be this step.
4222
4261
  */
4223
4262
  indoorSensitivity: {
4224
4263
  param: MOTION_CMD.INDOOR_SENSITIVITY_INDEX,
@@ -4226,7 +4265,8 @@ var MOTION_MEMBERS = {
4226
4265
  kind: "scalar",
4227
4266
  provenance: "verified",
4228
4267
  unexposed: true,
4229
- description: "Raw sensitivity an indoor camera reports (verified: param 6041)."
4268
+ description: "Raw sensitivity an indoor camera reports (verified: param 6041).",
4269
+ decode: (raw) => typeof raw === "number" ? raw : void 0
4230
4270
  },
4231
4271
  /**
4232
4272
  * The raw sensitivity on the INVERTED seven-step camera scale — a HIGHER number is LESS sensitive, so
@@ -5060,6 +5100,8 @@ var isIndoorCamera = (ctx) => has(INDOOR_CAMERA_TYPES, ctx.deviceType);
5060
5100
  var isIndoorCamMini = (ctx) => ctx.deviceType === DeviceType.INDOOR_COST_DOWN_CAMERA;
5061
5101
  var isIndoorPanTiltS350 = (ctx) => has(INDOOR_PT_S350_TYPES, ctx.deviceType);
5062
5102
  var isHomeBase = (ctx) => has(HOMEBASE_TYPES, ctx.deviceType);
5103
+ var isStation9000 = (ctx) => ctx.deviceType === DeviceType.STATION_9000;
5104
+ var isNvrT8N00 = (ctx) => ctx.model === "T8N00";
5063
5105
  var isAiotVacuum = (ctx) => ctx.category !== "eufy_home_tuya";
5064
5106
  var isTuyaVacuum = (ctx) => ctx.category === "eufy_home_tuya";
5065
5107
 
@@ -5205,6 +5247,8 @@ var AUDIO = {
5205
5247
 
5206
5248
  // dist/model/capabilities/camera.js
5207
5249
  var CAMERA_CMD = {
5250
+ /** Camera-reported Wi-Fi signal (app `CMD_GET_WIFI_RSSI`). */
5251
+ WIFI_RSSI: 1142,
5208
5252
  /** Camera on/off. Read and write polarity depend on the family and topology. */
5209
5253
  CAMERA_ENABLE: 1035,
5210
5254
  /** Wrapped T8410 power switch on HomeBase 3. */
@@ -5448,7 +5492,12 @@ function usesHomeBasePowerPayload(ctx) {
5448
5492
  function hasUnreflectedHomeBasePower(ctx) {
5449
5493
  return usesHomeBasePowerPayload(ctx) && !ctx.paramIds.has(2001);
5450
5494
  }
5495
+ function hasPrivacyPower(ctx) {
5496
+ return ctx.deviceType === DeviceType.INDOOR_PT_CAMERA_S350 && ctx.homeBaseAttached === true;
5497
+ }
5451
5498
  function powerCommand(on, ctx) {
5499
+ if (hasPrivacyPower(ctx))
5500
+ return privacyCommand(!on, ctx.channel);
5452
5501
  if (usesHomeBasePowerPayload(ctx))
5453
5502
  return setPayload(CAMERA_CMD.PRIVACY_MODE, { switch: on ? 0 : 1 }, ctx, 0);
5454
5503
  return setScalar(CAMERA_CMD.CAMERA_ENABLE, powerValue(on, ctx), ctx, "auto");
@@ -5465,11 +5514,11 @@ function poweredOf(ctx) {
5465
5514
  return cameraPowerTier(ctx.model, ctx.capabilities ?? /* @__PURE__ */ new Set());
5466
5515
  }
5467
5516
  function enablementReflection(on, ctx) {
5517
+ if (!CAMERA_MEMBERS.enabled.readReflectsWrite(ctx))
5518
+ return void 0;
5468
5519
  const alias = CAMERA_MEMBERS.enabled.readAliases[0].paramType;
5469
5520
  if (ctx.paramIds.has(alias))
5470
5521
  return { param: alias, expected: on, observed: on };
5471
- if (hasUnreflectedHomeBasePower(ctx))
5472
- return void 0;
5473
5522
  if (ctx.paramIds.has(CAMERA_CMD.CAMERA_ENABLE)) {
5474
5523
  return {
5475
5524
  param: CAMERA_CMD.CAMERA_ENABLE,
@@ -5480,10 +5529,18 @@ function enablementReflection(on, ctx) {
5480
5529
  return void 0;
5481
5530
  }
5482
5531
  function refuseWhenDisabled(ctx, read) {
5483
- if (!hasUnreflectedHomeBasePower(ctx) && read("enabled")?.value === false)
5532
+ if (CAMERA_MEMBERS.enabled.readReflectsWrite(ctx) && read("enabled")?.value === false)
5484
5533
  throw new CameraDisabledError(ctx.name ?? ctx.serial);
5485
5534
  }
5486
5535
  var CAMERA_MEMBERS = {
5536
+ /** Reads the latest cached report and exposes no setter. */
5537
+ wifiRssi: {
5538
+ param: CAMERA_CMD.WIFI_RSSI,
5539
+ type: "number",
5540
+ kind: "scalar",
5541
+ provenance: "apk",
5542
+ description: "Camera-reported Wi-Fi signal; physical units and a quality scale are unspecified."
5543
+ },
5487
5544
  /**
5488
5545
  * The default READ is the *disable*-bit convention (1035 "0" ⇒ ON, 2001 direct); the WRITE polarity is
5489
5546
  * family-dependent — see `powerValue` / `isEnableBitPolarity`. Battery/solo cams report the state under
@@ -5506,7 +5563,7 @@ var CAMERA_MEMBERS = {
5506
5563
  invert: true,
5507
5564
  invertFor: (ctx) => isT8410HomeBase3(ctx) ? false : void 0,
5508
5565
  readAliases: [{ paramType: 2001, invert: false }],
5509
- readReflectsWrite: (ctx) => !hasUnreflectedHomeBasePower(ctx),
5566
+ readReflectsWrite: (ctx) => !hasUnreflectedHomeBasePower(ctx) && !hasPrivacyPower(ctx),
5510
5567
  description: "Camera enabled. Family-dependent wire param: 1035 CMD_DEVS_SWITCH (enable bit on T8410/HomeBase 3, disable bit on battery/solo cams) or 2001 OPEN_DEVICE (standalone indoor/outdoor). Reported on/off state; unreflectedMembers identifies commands whose effect this report does not reliably reflect.",
5511
5568
  observation: {
5512
5569
  event: "cameraEnabledChanged",
@@ -5640,16 +5697,14 @@ var CAMERA_MEMBERS = {
5640
5697
  * Live-view quality, the pair to {@link CAMERA_MEMBERS.recordingQuality} and a different setting on a
5641
5698
  * different wire: changing one leaves the other's parameter untouched.
5642
5699
  *
5643
- * The READ is 1020, which reports the resolved tier as a plain integer. 1020 is also the name the
5644
- * param dictionary already gives that id, and `Device` keys state by NAME — a member claiming 2730
5645
- * under this name would collide with it on a device reporting both.
5700
+ * The READ is 1020, which reports the resolved tier as a plain integer, while the WRITE rides 2730's
5701
+ * `1350` payload. They are two ids for one setting because 2730 carries a per-mode config and 1020
5702
+ * carries the tier in force; the tier is what this property means. 1020 is also the name the param
5703
+ * dictionary already gives that id, and `Device` keys state by NAME — a member claiming 2730 under
5704
+ * this name would collide with it on a device reporting both.
5646
5705
  *
5647
- * `unverified: true` with no `write`: the app's 2730 frame is captured byte-exact, but replaying it
5648
- * from this SDK produced no observable change on a standalone T8171, where the recording sibling's
5649
- * 2731 write on the same envelope and the same session does land. The one difference the capture
5650
- * shows is that the app's frame carries no `mChannel`/`mValue3`, which this envelope always emits.
5651
- * Until a send is confirmed, the setter is absent — a control that silently does nothing is worse
5652
- * than none — and the read ships ahead of it, which verification per direction allows.
5706
+ * `transaction` is part of the frame that was captured, so it is sent. The recording sibling's own
5707
+ * confirmed frame carries no such field; neither is inferred from the other.
5653
5708
  */
5654
5709
  streamingQuality: {
5655
5710
  param: 1020,
@@ -5657,8 +5712,13 @@ var CAMERA_MEMBERS = {
5657
5712
  kind: "enum",
5658
5713
  enumValues: STREAMING_QUALITY_TIERS,
5659
5714
  provenance: "verified",
5660
- unverified: true,
5661
- description: "Live-view quality as a tier, 0 = Auto (1020). Distinct from recordingQuality, which is what gets stored. All four tiers confirmed on a T8170 and a T8171. The WRITE (2730) is unconfirmed from this SDK, so no setter is offered rather than one that reports success without acting \u2014 see CAMERA_CMD.STREAMING_QUALITY_SET."
5715
+ args: [{ name: "quality", kind: "enum", description: "A tier, or the name it maps to. 0 is Auto." }],
5716
+ ...accepts(),
5717
+ description: "Live-view quality as a tier, 0 = Auto (1020; the write rides 2730 APP_CMD_MULTI_CAM_SET_VIDEO_QUALITY). Distinct from recordingQuality, which is what gets stored. All four tiers wire-verified live on a T8170 and read back on 1020. Sent from this SDK to a standalone T8170 and T8171, tier 1 holds the live stream at 1280x720 and tier 0 restores the camera's own resolution ladder \u2014 see CAMERA_CMD.STREAMING_QUALITY_SET. A value outside the tier set is REJECTED, not clamped: every tier in range is a real quality, so a bad one would silently pick another.",
5718
+ write: (v, ctx) => {
5719
+ const q = resolveStreamingQualityTier(v);
5720
+ return q == null ? void 0 : setPayload(CAMERA_CMD.STREAMING_QUALITY_SET, { channel: 0, mode: 0, primary_view: 0, quality: q, transaction: String(Date.now()) }, ctx, 0, void 0, "auto");
5721
+ }
5662
5722
  },
5663
5723
  /**
5664
5724
  * `type` is how the value is STORED, and 2731 stores the whole config — the ACTIVE tier is lifted out
@@ -5829,8 +5889,9 @@ function isStationAlarmOutput(ctx) {
5829
5889
  function isEvidencedStationAlarm(ctx) {
5830
5890
  return isStationAlarmOutput(ctx) && HUB_ALARM_EVIDENCE.some((param) => ctx.paramIds.has(param));
5831
5891
  }
5892
+ var S1_PRO_ALARM_MODELS = /* @__PURE__ */ new Set(["T8134"]);
5832
5893
  function isEvidencedAttachedCamera(ctx) {
5833
- return ctx.codec === "camera" && ctx.homeBaseAttached === true && hasReportedEasSwitch(ctx);
5894
+ return ctx.codec === "camera" && ctx.homeBaseAttached === true && hasReportedEasSwitch(ctx) && (!isStation9000({ deviceType: ctx.stationDeviceType }) || S1_PRO_ALARM_MODELS.has(ctx.model ?? ""));
5834
5895
  }
5835
5896
  function reportsParam(source, param) {
5836
5897
  return source.paramIds?.has(param) === true || Object.hasOwn(source.params ?? {}, param);
@@ -5849,7 +5910,18 @@ function homeBaseAlarm(seconds, ctx) {
5849
5910
  throw new Error("station-family HomeBase alarm output requires the acting account name");
5850
5911
  return setPayload(SIREN_CMD.HOMEBASE_TONE, { time_out: seconds, user_name: ctx.accountName }, ctx, 0, STATION_CHANNEL);
5851
5912
  }
5913
+ var PORTAL_MANUAL_ALARM_TYPE = 10;
5852
5914
  function cameraAlarm(seconds, ctx) {
5915
+ if (isStation9000({ deviceType: ctx.stationDeviceType })) {
5916
+ if (!ctx.accountName)
5917
+ throw new Error("a camera alarm behind a HomeBase S1 Pro requires the acting account name");
5918
+ return setPayload(SIREN_CMD.CAMERA_TONE, {
5919
+ time_out: seconds,
5920
+ type: PORTAL_MANUAL_ALARM_TYPE,
5921
+ channel: ctx.channel,
5922
+ username: ctx.accountName
5923
+ }, ctx);
5924
+ }
5853
5925
  return {
5854
5926
  kind: "p2p-int-string",
5855
5927
  cmd: SIREN_CMD.CAMERA_TONE,
@@ -6093,7 +6165,8 @@ var LIGHT_SWITCH_INT_STRING_TYPES = /* @__PURE__ */ new Set([
6093
6165
  DeviceType.CAMERA2_PRO,
6094
6166
  DeviceType.CAMERA2C_PRO,
6095
6167
  DeviceType.CAMERA3,
6096
- DeviceType.CAMERA3C
6168
+ DeviceType.CAMERA3C,
6169
+ DeviceType.PROFESSIONAL_247
6097
6170
  ]);
6098
6171
  function switchCommand(on, ctx) {
6099
6172
  switch (lightSwitchWire(ctx)) {
@@ -6188,6 +6261,9 @@ var LIGHT_MEMBERS = {
6188
6261
  * This is the switch a user changes and expects to STAY changed. {@link isOn} is a different fact:
6189
6262
  * the lamp being lit right now, driven by whichever
6190
6263
  * client is streaming — the vendor app lights it for a live view and drops it on quitting.
6264
+ *
6265
+ * The T8423 write takes the session-chosen level; level-1 int+string was verified live on a standalone
6266
+ * unit.
6191
6267
  */
6192
6268
  spotlightEnabled: {
6193
6269
  param: LIGHT_CMD.SPOTLIGHT_ENABLE,
@@ -6195,7 +6271,7 @@ var LIGHT_MEMBERS = {
6195
6271
  kind: "boolean",
6196
6272
  provenance: "verified",
6197
6273
  description: "The spotlight master switch, distinct from the on/off above \u2014 whether the spotlight may light at all. Read verified live on a T8170 (param 1403, direct polarity: 1 = enabled).",
6198
- write: (v, ctx) => directBinary(LIGHT_CMD.SPOTLIGHT_ENABLE, asBool(v) ? 1 : 0, ctx),
6274
+ write: (v, ctx) => setScalar(LIGHT_CMD.SPOTLIGHT_ENABLE, asBool(v) ? 1 : 0, ctx, ctx.deviceType === DeviceType.FLOODLIGHT_CAMERA_8423 ? "auto" : "direct-binary"),
6199
6275
  writeAs: "setEnabled"
6200
6276
  }
6201
6277
  };
@@ -6588,6 +6664,8 @@ var ZOOM_MODEL_HINT = /^T8170\b|^T8425\b|S340/i;
6588
6664
  function hasZoomEvidence(ctx) {
6589
6665
  return ZOOM_EVIDENCE_PARAMS.some((p) => ctx.paramIds.has(p)) || !!ctx.model && ZOOM_MODEL_HINT.test(ctx.model);
6590
6666
  }
6667
+ var PRESET_EVIDENCE_PARAMS = [1029, 6090, 6091, 6092, 6210];
6668
+ var FIXED_LENS_MODELS = /* @__PURE__ */ new Set(["T8134"]);
6591
6669
  function rotateCommand(direction, ctx, zoom = 1) {
6592
6670
  return setJson(PTZ_CMD.PTZ_ROTATE, { cmd_type: 1, rotate_type: PTZ_ROTATE[direction], zoom }, ctx);
6593
6671
  }
@@ -6752,8 +6830,9 @@ var PTZ = {
6752
6830
  members: PTZ_MEMBERS,
6753
6831
  properties: propertiesOf(PTZ_MEMBERS),
6754
6832
  // SoloCam proves PT via reported preset params (6090/6091/6092/6210) and a rotate command surface
6755
- // (1029); Indoor-PT (deviceType 31/35/111 + C220 range 10008-10011) reports NO PT param, so the
6756
- // vendor deviceType is the only honest signal; explicit PT/S340/S350 model names also prove it.
6833
+ // (1029), except on a FIXED_LENS_MODELS model; Indoor-PT (deviceType 31/35/111 + C220 range
6834
+ // 10008-10011) reports NO PT param, so the vendor deviceType is the only honest signal; explicit
6835
+ // PT/S340/S350 model names also prove it.
6757
6836
  // OUTDOOR_PT_CAMERA (48, e.g. SoloCam S340 / T8170) is pan-tilt by definition but a live unit can
6758
6837
  // report none of the preset params — trust the deviceType. The rotating SoloCam solar variant
6759
6838
  // T8124R shares deviceType 62 with the FIXED T8124 base, so its model code is the only honest
@@ -6761,7 +6840,7 @@ var PTZ = {
6761
6840
  // a `T81\d\dR` wildcard: the "R = rotating" reading is unverified for other models, and an
6762
6841
  // over-broad hint would false-positive a future non-PT model, the same class of bug as a mislabel.
6763
6842
  detection: {
6764
- evidenceParams: [1029, 6090, 6091, 6092, 6210],
6843
+ detect: (record) => !FIXED_LENS_MODELS.has(record.model ?? "") && PRESET_EVIDENCE_PARAMS.some((p) => Object.hasOwn(record.params ?? {}, p)),
6765
6844
  deviceTypes: [
6766
6845
  DeviceType.OUTDOOR_PT_CAMERA,
6767
6846
  DeviceType.INDOOR_PT_CAMERA,
@@ -6777,7 +6856,7 @@ var PTZ = {
6777
6856
  // no PTZ capability without this, on a real owned unit.
6778
6857
  DeviceType.FLOODLIGHT_CAMERA_8425
6779
6858
  ],
6780
- modelHints: [/pan.?tilt|\bpt\b|S3[45]0|indoor.?pt/i]
6859
+ modelHints: [/pan.?tilt|\bpt\b|S3[45]0|indoor.?pt/i, /\bT8E00\b/i]
6781
6860
  },
6782
6861
  emits: ["ptzNotify"],
6783
6862
  /**
@@ -7632,7 +7711,8 @@ var ARMING_CMD = {
7632
7711
  */
7633
7712
  SET_ARMING: 1224,
7634
7713
  /**
7635
- * The per-mode alarm/arm-delay configuration write. ✅ WIRE CAPTURED live on a T8030 (
7714
+ * One guard mode's per-device action table (app `CMD_SET_ALL_ACTION`), which carries the alarm delays
7715
+ * and each device's actions in that mode. ✅ WIRE CAPTURED live on a T8030 (
7636
7716
  * 2026-07-23, both directions): a **bare
7637
7717
  * JSON frame, no `1350`/`1700` envelope** — outer P2P cmd IS `1255` itself, station channel 255,
7638
7718
  * plaintext `{account_id, count_down_alarm:{channel_list,delay_time},
@@ -7649,15 +7729,26 @@ var ARMING_CMD = {
7649
7729
  * corresponding GET command (`1310`/inner cmd `40003`, sent by the app right before editing) always
7650
7730
  * replied `{count:0,data:null}` in every capture — genuinely empty, not a decrypt failure (confirmed
7651
7731
  * via the same bidirectional decrypt this finding used) — so the app does NOT read the current
7652
- * config this way; how it does is still unknown. Without a working GET, safely PATCHING just one
7653
- * channel in or out of an existing list isn't possible without risking clobbering the rest — so
7732
+ * config this way; a T8010 reports it on its own params instead, see below. Without a working GET,
7733
+ * safely PATCHING just one channel in or out of an existing list isn't possible without risking
7734
+ * clobbering the rest — so
7654
7735
  * this ships as a caller-supplies-everything write instead of guessing a merge.
7655
7736
  * `devices`/`siren_sensor_action` are even less understood (raw per-device action codes, meaning
7656
7737
  * unconfirmed) and MUST come from a value independently read/captured for the target mode —
7657
7738
  * see `AlarmDelayConfig`'s field docs.
7739
+ *
7740
+ * ✅ On a T8010 the app writes the same command for the Device Control screen: header channel 0, the
7741
+ * whole table of the mode `{mode_id, devices, count_down_alarm, count_down_arm}`, acked by an all-zero
7742
+ * 1255 reply. The T8010 reports each table on its own params, Home on 1157 and Away on 1158, and the
7743
+ * reported table follows a write within 15 s. See {@link DEVICE_NOTIFY_FLAG}.
7658
7744
  */
7659
- ALARM_DELAY_CONFIG: 1255
7745
+ SET_ALL_ACTION: 1255
7660
7746
  };
7747
+ var DEVICE_NOTIFY_FLAG = 8;
7748
+ function actionTable(read, mode) {
7749
+ const value = read(`${mode}ActionTable`)?.value;
7750
+ return value && typeof value === "object" && Array.isArray(value.devices) ? value : void 0;
7751
+ }
7661
7752
  var ARMING_MODE_WIRE = {
7662
7753
  away: 0,
7663
7754
  home: 1,
@@ -7694,7 +7785,15 @@ function alarmDelayCommand(mode, config, ctx) {
7694
7785
  devices: config.devices.map((d) => ({ action: d.action, device_channel: d.deviceChannel })),
7695
7786
  siren_sensor_action: config.sirenSensorAction.map((d) => ({ action: d.action, device_channel: d.deviceChannel }))
7696
7787
  };
7697
- return setJsonRaw(ARMING_CMD.ALARM_DELAY_CONFIG, data, ctx, STATION_CHANNEL2);
7788
+ return setJsonRaw(ARMING_CMD.SET_ALL_ACTION, data, ctx, STATION_CHANNEL2);
7789
+ }
7790
+ var ACTION_TABLE_LAG_MS = 15e3;
7791
+ function withDeviceNotification(table, channel, on) {
7792
+ if (!table?.devices.some((d) => d.device_channel === channel))
7793
+ return void 0;
7794
+ const { account_id: _account, ...rest } = table;
7795
+ const devices = table.devices.map((d) => d.device_channel === channel ? { ...d, action: on ? d.action | DEVICE_NOTIFY_FLAG : d.action & ~DEVICE_NOTIFY_FLAG } : d);
7796
+ return { ...rest, devices };
7698
7797
  }
7699
7798
  var ARMING_MEMBERS = {
7700
7799
  /**
@@ -7752,7 +7851,45 @@ var ARMING_MEMBERS = {
7752
7851
  } catch (e) {
7753
7852
  return Promise.reject(e);
7754
7853
  }
7755
- }, "Write the full per-mode alarm/arm-delay configuration.")
7854
+ }, "Write the full per-mode alarm/arm-delay configuration."),
7855
+ /**
7856
+ * Whether the device on `channel` sends a push notification in `mode`: its {@link DEVICE_NOTIFY_FLAG}
7857
+ * in the action table the station reports for that mode. `undefined` where the station reports no table
7858
+ * or the table does not list `channel`. A device's channel is `EufyDevice.channel`.
7859
+ */
7860
+ deviceNotification: method(({ read }) => (mode, channel) => {
7861
+ const action = actionTable(read, mode)?.devices.find((d) => d.device_channel === channel)?.action;
7862
+ return typeof action === "number" ? (action & DEVICE_NOTIFY_FLAG) !== 0 : void 0;
7863
+ }, "Whether the device on a channel sends a push notification in a guard mode (home/away).", (ctx) => ctx.model === "T8010"),
7864
+ /**
7865
+ * Turn the push notification of the device on `channel` on or off in `mode` (cmd
7866
+ * {@link ARMING_CMD.SET_ALL_ACTION}): the station's reported table written back with that one flag
7867
+ * changed. Rejects, sending nothing, where the table does not list `channel`. A write builds on the last
7868
+ * one sent for that mode until the station reports a table observed 15 s after it, so a second write does
7869
+ * not revert it; a write whose dispatch rejects is not built on.
7870
+ */
7871
+ setDeviceNotification: method(({ ctx, sink, read }) => {
7872
+ const sent = /* @__PURE__ */ new Map();
7873
+ return (mode, channel, on) => {
7874
+ const last = sent.get(mode);
7875
+ const observed = read(`${mode}ActionTable`)?.ts ?? 0;
7876
+ const base = last && observed < last.at + ACTION_TABLE_LAG_MS ? last.table : actionTable(read, mode);
7877
+ const table = withDeviceNotification(base, channel, on);
7878
+ if (!table) {
7879
+ return Promise.reject(new Error(`arming: no ${mode} action table lists channel ${channel} [${describeDevice(ctx)}]`));
7880
+ }
7881
+ sent.set(mode, { table, at: Date.now() });
7882
+ return sink.dispatch(setJsonRaw(ARMING_CMD.SET_ALL_ACTION, table, ctx, 0)).catch((err) => {
7883
+ if (sent.get(mode)?.table === table) {
7884
+ if (last)
7885
+ sent.set(mode, last);
7886
+ else
7887
+ sent.delete(mode);
7888
+ }
7889
+ throw err;
7890
+ });
7891
+ };
7892
+ }, "Turn the push notification of the device on a channel on or off in a guard mode (home/away).", (ctx) => ctx.model === "T8010")
7756
7893
  };
7757
7894
  var ARMING = {
7758
7895
  capability: "arming",
@@ -8312,8 +8449,6 @@ var MODE_CTRL_FIELD = {
8312
8449
  SEQ: 2
8313
8450
  };
8314
8451
  var ModeCtrlMethod = {
8315
- /** Live-verified on a T2351. Zero, so it is omitted from the wire per the proto3 default rule. */
8316
- START_AUTO_CLEAN: 0,
8317
8452
  /** Live-verified on a T2351. */
8318
8453
  START_GOHOME: 6,
8319
8454
  /** Live-verified on a T2351. */
@@ -8337,6 +8472,8 @@ var ModeCtrlMethod = {
8337
8472
  START_GLOBAL_CRUISE: 20
8338
8473
  };
8339
8474
  var ModeCtrlParamMethod = {
8475
+ /** `START_AUTO_CLEAN` with an `AutoClean` payload — clean the whole floor. */
8476
+ AUTO: { method: 0, param: 3 },
8340
8477
  /** `START_SELECT_ROOMS_CLEAN` — clean the named rooms of a named map. */
8341
8478
  SELECT_ROOMS: { method: 1, param: 4 },
8342
8479
  /** `START_SELECT_ZONES_CLEAN` — clean the given rectangles of a named map. */
@@ -8373,6 +8510,7 @@ var SELECT_ZONES_FIELD = {
8373
8510
  POINT_Y: 2
8374
8511
  };
8375
8512
  var SCENE_CLEAN_ID = 1;
8513
+ var AUTO_CLEAN_TIMES = 1;
8376
8514
  function encodeModeCtrlParam(method2, paramField, build) {
8377
8515
  return rawDp((w) => {
8378
8516
  if (method2 !== 0)
@@ -8419,14 +8557,17 @@ function encodeSceneClean(sceneId) {
8419
8557
  const { method: method2, param } = ModeCtrlParamMethod.SCENE;
8420
8558
  return encodeModeCtrlParam(method2, param, (p) => p.int(SCENE_CLEAN_ID, sceneId));
8421
8559
  }
8560
+ function encodeAutoClean() {
8561
+ const { method: method2, param } = ModeCtrlParamMethod.AUTO;
8562
+ return encodeModeCtrlParam(method2, param, (p) => p.int(AUTO_CLEAN_TIMES, 1));
8563
+ }
8422
8564
  var modeCtrlSeq = 111;
8423
8565
  function nextModeCtrlSeq() {
8424
8566
  return ++modeCtrlSeq;
8425
8567
  }
8426
8568
  function encodeModeCtrl(method2, seq) {
8427
8569
  return rawDp((w) => {
8428
- if (method2 !== 0)
8429
- w.int(MODE_CTRL_FIELD.METHOD, method2);
8570
+ w.int(MODE_CTRL_FIELD.METHOD, method2);
8430
8571
  w.int(MODE_CTRL_FIELD.SEQ, seq);
8431
8572
  });
8432
8573
  }
@@ -10268,8 +10409,8 @@ var VACUUM_CLEAN_MEMBERS = {
10268
10409
  provenance: "mega",
10269
10410
  description: "Stop smart-follow mode (ModeCtrlRequest method 18 over DP 152). Method number not captured \u2014 unverified."
10270
10411
  },
10271
- /** Start an auto-clean run via ModeCtrlRequest method 0 (DP 152). AIoT only — Tuya write unverified. */
10272
- startCleaning: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeModeCtrl(ModeCtrlMethod.START_AUTO_CLEAN, nextModeCtrlSeq()))), "Start an auto-clean run (ModeCtrlRequest method 0 over DP 152).", isAiotVacuum),
10412
+ /** Start an auto-clean run via ModeCtrlRequest method 0 with one `AutoClean` pass (DP 152). AIoT only — Tuya write unverified. */
10413
+ startCleaning: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeAutoClean())), "Start an auto-clean run (ModeCtrlRequest method 0, AutoClean clean_times 1, over DP 152).", isAiotVacuum),
10273
10414
  /** Return to the dock via ModeCtrlRequest method 6 (DP 152). AIoT only — Tuya write unverified. */
10274
10415
  returnToDock: method(({ sink }) => () => sink.dispatch(aiotDp(VACUUM_DP.MODE_CTRL, encodeModeCtrl(ModeCtrlMethod.START_GOHOME, nextModeCtrlSeq()))), "Return to the dock (ModeCtrlRequest method 6 over DP 152).", isAiotVacuum),
10275
10416
  /** Pause the current cleaning task via ModeCtrlRequest method 13 (DP 152). AIoT only — Tuya write unverified. */
@@ -10392,6 +10533,11 @@ var SuctionLevel = {
10392
10533
  };
10393
10534
  var SUCTION_LABEL = enumLabels(SuctionLevel);
10394
10535
  var ALL_SUCTION_LEVELS = [0, 1, 2, 3, 4, 5];
10536
+ function levelFromCatalog(member) {
10537
+ if (Object.hasOwn(SuctionLevel, member))
10538
+ return SuctionLevel[member];
10539
+ return Object.hasOwn(SUCTION_LABEL, member) ? Number(member) : void 0;
10540
+ }
10395
10541
  function suctionLevelName(value) {
10396
10542
  return SUCTION_LABEL[value];
10397
10543
  }
@@ -10452,13 +10598,15 @@ var SUCTION = {
10452
10598
  },
10453
10599
  /**
10454
10600
  * The per-model level range — sourced from the SKU's `get_product_data_point` catalog for DP 158
10455
- * when available. `undefined` when no catalog entry exists for DP 158. `setSuctionLevel` is only
10601
+ * when available. `undefined` when no catalog entry exists for DP 158, or when no listed member maps
10602
+ * to a known level (so a caller never reads `[]` as "nothing selectable"). `setSuctionLevel` is only
10456
10603
  * installed on AIoT devices (gated by `available: isAiotVacuum` on the `level` entry), so
10457
10604
  * `supportedLevels` is harmless data on a non-AIoT device.
10458
10605
  */
10459
10606
  actions({ ctx }) {
10460
10607
  const catalogRange = ctx.dpCatalog?.enumRanges.get(SUCTION_DP.SUCTION);
10461
- const supportedLevels = catalogRange?.filter((v) => v in SUCTION_LABEL);
10608
+ const levels = catalogRange?.flatMap((m) => levelFromCatalog(m) ?? []);
10609
+ const supportedLevels = levels?.length ? levels : void 0;
10462
10610
  return { supportedLevels };
10463
10611
  }
10464
10612
  };
@@ -10500,28 +10648,29 @@ function parseEnumRange(values) {
10500
10648
  if (values === null || values === void 0)
10501
10649
  return [];
10502
10650
  if (Array.isArray(values))
10503
- return toNumberArray(values);
10651
+ return toMemberArray(values);
10504
10652
  if (typeof values === "string") {
10505
10653
  try {
10506
10654
  const parsed = JSON.parse(values);
10507
10655
  if (Array.isArray(parsed))
10508
- return toNumberArray(parsed);
10656
+ return toMemberArray(parsed);
10509
10657
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
10510
10658
  const obj = parsed;
10511
10659
  if (Array.isArray(obj.range))
10512
- return toNumberArray(obj.range);
10660
+ return toMemberArray(obj.range);
10513
10661
  }
10514
10662
  } catch {
10515
10663
  }
10516
10664
  }
10517
10665
  return [];
10518
10666
  }
10519
- function toNumberArray(arr) {
10667
+ function toMemberArray(arr) {
10520
10668
  const result = [];
10521
10669
  for (const v of arr) {
10522
- const n = typeof v === "number" ? v : typeof v === "string" ? Number(v) : NaN;
10523
- if (Number.isInteger(n))
10524
- result.push(n);
10670
+ if (typeof v === "number" && Number.isFinite(v))
10671
+ result.push(String(v));
10672
+ else if (typeof v === "string" && v !== "")
10673
+ result.push(v);
10525
10674
  }
10526
10675
  return result;
10527
10676
  }
@@ -11016,8 +11165,12 @@ var MODEL_REGISTRY = {
11016
11165
  // Cameras with curated extras that aren't always provable from a fresh device's params.
11017
11166
  T8423: { codec: "camera", caps: ["light", "battery"], name: "Floodlight Cam" },
11018
11167
  T8210: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell" },
11168
+ // T8210 hardware variant, reported as its own code; shares the T8210 row.
11169
+ T8210C: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell" },
11019
11170
  // Confirmed against a real owned unit (named "Doorbell"): Video Doorbell Dual.
11020
11171
  T8214: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell Dual" },
11172
+ // Battery Video Doorbell Dual, vendor deviceType 91 (BATTERY_DOORBELL_PLUS), reported by two users.
11173
+ T8213: { codec: "camera", caps: ["doorbell", "battery"], name: "Video Doorbell Dual" },
11021
11174
  // Confirmed against a real owned unit: the mains-powered Wired Doorbell 2K. No `battery` row
11022
11175
  // member on purpose — this model is wired, so the codec baseline plus inference is the whole
11023
11176
  // truth for power. Without this row it classified as a plain camera, so the doorbell capability
@@ -11179,8 +11332,10 @@ function resolveDevice(rec) {
11179
11332
  }
11180
11333
  function resolveProperties(rec, codec, capabilities) {
11181
11334
  const paramIds = /* @__PURE__ */ new Set();
11182
- if (rec.params && typeof rec.params === "object") {
11183
- for (const k of Object.keys(rec.params)) {
11335
+ for (const reported of [rec.params, rec.dpParams]) {
11336
+ if (!reported || typeof reported !== "object")
11337
+ continue;
11338
+ for (const k of Object.keys(reported)) {
11184
11339
  const n = Number(k);
11185
11340
  if (Number.isFinite(n))
11186
11341
  paramIds.add(n);
@@ -11380,9 +11535,15 @@ var SECURITY_PARAMS = {
11380
11535
  provenance: "guessed"
11381
11536
  },
11382
11537
  1157: {
11383
- name: "jsDelayHome",
11538
+ name: "homeActionTable",
11384
11539
  type: "string",
11385
- provenance: "apk",
11540
+ provenance: "verified",
11541
+ encoding: "base64+json"
11542
+ },
11543
+ 1158: {
11544
+ name: "awayActionTable",
11545
+ type: "string",
11546
+ provenance: "verified",
11386
11547
  encoding: "base64+json"
11387
11548
  },
11388
11549
  1159: {
@@ -14383,6 +14544,19 @@ function decodeMapFrame(frame, codec) {
14383
14544
  return READERS.get(frame.channelId)?.(frame.payload, codec);
14384
14545
  }
14385
14546
 
14547
+ // dist/transport/abortable.js
14548
+ function abortable(work, signal) {
14549
+ if (!signal)
14550
+ return work;
14551
+ signal.throwIfAborted();
14552
+ return Promise.race([
14553
+ work,
14554
+ new Promise((_resolve, reject) => {
14555
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
14556
+ })
14557
+ ]);
14558
+ }
14559
+
14386
14560
  // dist/transport/p2p/command-router.js
14387
14561
  import { setTimeout as sleep2 } from "node:timers/promises";
14388
14562
 
@@ -15308,7 +15482,7 @@ var PADDED_RESULT_BYTES = 132;
15308
15482
  var CMD_CAMERA_INFO = 1103;
15309
15483
  var CMD_DATABASE_IMAGE = 1308;
15310
15484
  var CMD_DATABASE = 1306;
15311
- var DB_QUERY = { FULL_TABLE: 1e4, COMBINATION_WITH_AI: 10011 };
15485
+ var DB_QUERY = { FULL_TABLE: 1e4, COMBINATION_WITH_AI: 10011, QUERY_LOCAL: 10017 };
15312
15486
  var GCM_AAD = Buffer.from("eufy security");
15313
15487
  var LEVEL2_SEQ_BASE = 16909056;
15314
15488
  function paramReport(payload) {
@@ -15338,9 +15512,13 @@ function firstTableRows(text2) {
15338
15512
  } catch {
15339
15513
  continue;
15340
15514
  }
15341
- const data = parsed?.data;
15342
- if (Array.isArray(data))
15343
- return data;
15515
+ const reply = parsed;
15516
+ if (typeof reply?.mIntRet === "number" && reply.mIntRet !== 0)
15517
+ return { error: reply.mIntRet };
15518
+ if (reply?.data === "[]")
15519
+ return { rows: [] };
15520
+ if (Array.isArray(reply?.data))
15521
+ return { rows: reply.data };
15344
15522
  }
15345
15523
  return void 0;
15346
15524
  }
@@ -15699,8 +15877,8 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
15699
15877
  return this.connected;
15700
15878
  }
15701
15879
  /**
15702
- * Ask the OS for {@link RECEIVE_BUFFER_BYTES} on a bound socket, and warn once per session when it grants
15703
- * less or refuses.
15880
+ * Ask the OS for {@link RECEIVE_BUFFER_BYTES} on a bound socket, and log once per session when it grants
15881
+ * less (debug) or refuses (warn).
15704
15882
  *
15705
15883
  * The request is made here rather than through `createSocket`'s `recvBufferSize`: Node applies that option
15706
15884
  * inside the bind callback, where a refusal is thrown out of reach of this session and ends the process.
@@ -15716,7 +15894,8 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
15716
15894
  if (granted >= RECEIVE_BUFFER_BYTES || this.receiveBufferReported)
15717
15895
  return;
15718
15896
  this.receiveBufferReported = true;
15719
- this.logger.warn(`[p2p] ${this.cfg.stationSn} UDP receive buffer below the ${RECEIVE_BUFFER_BYTES} bytes requested` + (granted > 0 ? ` (granted ${granted})` : " (request refused)") + `; live video can lose keyframes. Raise the OS limit (net.core.rmem_max on Linux, kern.ipc.maxsockbuf on BSD) to at least ${RECEIVE_BUFFER_BYTES}.`);
15897
+ const [level, outcome] = granted > 0 ? ["debug", ` (granted ${granted})`] : ["warn", " (request refused)"];
15898
+ this.logger[level](`[p2p] ${this.cfg.stationSn} UDP receive buffer below the ${RECEIVE_BUFFER_BYTES} bytes requested` + outcome + `; live video can lose keyframes. Raise the OS limit (net.core.rmem_max on Linux, kern.ipc.maxsockbuf on BSD) to at least ${RECEIVE_BUFFER_BYTES}.`);
15720
15899
  }
15721
15900
  /** Open the socket and start the lookup → hole-punch handshake. */
15722
15901
  async connect() {
@@ -15961,6 +16140,7 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
15961
16140
  socket.removeAllListeners("error");
15962
16141
  socket.on("error", (error) => this.emit("error", error));
15963
16142
  this.socket = socket;
16143
+ this.requestReceiveBuffer(socket);
15964
16144
  }
15965
16145
  this.connected = true;
15966
16146
  this.connectedAtMs = Date.now();
@@ -16248,6 +16428,21 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16248
16428
  this.send(this.connectAddress, RequestMessageType.DATA, data);
16249
16429
  return true;
16250
16430
  }
16431
+ /**
16432
+ * The level-1 twin of {@link sendRawLevel2Bytes}: the plaintext `payload` sealed AES-128-ECB under the
16433
+ * level-1 key, signCode 1 — the seal of the level-1 media start. Returns `false` when not connected.
16434
+ */
16435
+ sendRawLevel1Bytes(payload, channel, outerCmd) {
16436
+ if (!this.connectAddress)
16437
+ return false;
16438
+ const data = Buffer.concat([
16439
+ buildCommandHeader(this.seqNumber, outerCmd),
16440
+ buildRawCommandPayload(encryptP2PData(paddingP2PData(payload), this.level1Key), channel, 1)
16441
+ ]);
16442
+ this.seqNumber = this.seqNumber + 1 & 65535;
16443
+ this.send(this.connectAddress, RequestMessageType.DATA, data);
16444
+ return true;
16445
+ }
16251
16446
  /**
16252
16447
  * Stop the realtime media stream (`CMD_STOP_REALTIME_MEDIA`, 1004) on a camera `channel`, in the shape
16253
16448
  * its runtime topology takes, as {@link startLiveMedia} selects its start:
@@ -16468,7 +16663,7 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16468
16663
  camera_type: 0,
16469
16664
  entrytype: 0,
16470
16665
  key: this.rsaModulus(),
16471
- streamtype: 1,
16666
+ streamtype: 2,
16472
16667
  ...payload
16473
16668
  } : payload;
16474
16669
  const value = JSON.stringify({
@@ -16684,6 +16879,29 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16684
16879
  query: this.fullTableQuery()
16685
16880
  });
16686
16881
  }
16882
+ /**
16883
+ * Read a date-ranged page of `history_record_info` from the station. The reply's `data` array groups
16884
+ * recording rows with companion tables; each group retains its `table_name` and `payload`.
16885
+ * `startTime` is `"0"` for the newest page or the oldest row's `yyyyMMddHHmmss` cursor for older rows.
16886
+ */
16887
+ queryRecordPage(opts) {
16888
+ return this.readDatabase("history_record_info", {
16889
+ accountId: opts.accountId,
16890
+ innerCmd: DB_QUERY.QUERY_LOCAL,
16891
+ query: {
16892
+ count: opts.count ?? 20,
16893
+ start_date: opts.startDate,
16894
+ end_date: opts.endDate,
16895
+ start_time: opts.startTime ?? "0",
16896
+ event_type: 0,
16897
+ ai_type: 0,
16898
+ storage_cloud: -1,
16899
+ trigger_type: 0,
16900
+ detection_type: 0,
16901
+ flag: 0
16902
+ }
16903
+ });
16904
+ }
16687
16905
  /**
16688
16906
  * Query one on-station table and answer its rows, once the reply is whole.
16689
16907
  *
@@ -16691,7 +16909,7 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16691
16909
  * several frames whose decrypted text is a fragment of one document, so the fragments are
16692
16910
  * accumulated here and scanned after each one. Answers that document's `data` rows. Rejects when
16693
16911
  * `signal` aborts, and when `timeoutMs` (default {@link DB_TABLE_TIMEOUT_MS}) elapses with no
16694
- * complete reply.
16912
+ * complete reply, and when the station answers a non-zero `mIntRet`.
16695
16913
  *
16696
16914
  * One read at a time per session: while one is accumulating, every {@link queryDatabase} on the
16697
16915
  * session throws, so a second reply cannot land in this buffer.
@@ -16699,16 +16917,22 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16699
16917
  async readDatabase(table, opts = {}) {
16700
16918
  if (opts.signal?.aborted)
16701
16919
  throw new Error("readDatabase: aborted");
16702
- this.queryDatabase(table, { accountId: opts.accountId, query: this.fullTableQuery() });
16920
+ this.queryDatabase(table, {
16921
+ accountId: opts.accountId,
16922
+ innerCmd: opts.innerCmd,
16923
+ query: opts.query ?? this.fullTableQuery()
16924
+ });
16703
16925
  this.dbReadInFlight = true;
16704
16926
  try {
16705
16927
  return await new Promise((resolve, reject) => {
16706
16928
  let text2 = "";
16707
16929
  const onChunk = (chunk) => {
16708
16930
  text2 += chunk.text;
16709
- const rows = firstTableRows(text2);
16710
- if (rows)
16711
- settle(() => resolve(rows));
16931
+ const result = firstTableRows(text2);
16932
+ if (result?.error !== void 0)
16933
+ settle(() => reject(new Error(`readDatabase: ${table} refused: ${result.error}`)));
16934
+ else if (result?.rows)
16935
+ settle(() => resolve(result.rows));
16712
16936
  };
16713
16937
  const timer = setTimeout(() => settle(() => reject(new Error(`readDatabase: ${this.cfg.stationSn} sent no complete ${table}`))), opts.timeoutMs ?? DB_TABLE_TIMEOUT_MS);
16714
16938
  const onAbort = () => settle(() => reject(new Error("readDatabase: aborted")));
@@ -16809,11 +17033,13 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16809
17033
  if (advance > SEQUENCE_LOOKBACK) {
16810
17034
  if (65536 - advance <= STALE_RETRANSMIT_DEPTH)
16811
17035
  return;
16812
- if (this.pendingByDataType.has(dataType) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
17036
+ if ((dataType === P2PDataType.VIDEO || this.pendingByDataType.has(dataType)) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16813
17037
  this.trace({ phase: "sequence-restart", dataType });
16814
17038
  this.clearReorderTimer(dataType);
16815
17039
  this.reorderByType.delete(dataType);
16816
17040
  this.pendingByDataType.delete(dataType);
17041
+ if (dataType === P2PDataType.VIDEO)
17042
+ this.emit("videoGap");
16817
17043
  this.lastSeqByType.set(dataType, seqNo);
16818
17044
  this.reassemble(dataType, msg.subarray(8));
16819
17045
  return;
@@ -16879,9 +17105,11 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16879
17105
  */
16880
17106
  abandonHole(dataType) {
16881
17107
  const held = this.reorderByType.get(dataType).held;
16882
- if (this.pendingByDataType.has(dataType) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
17108
+ if ((dataType === P2PDataType.VIDEO || this.pendingByDataType.has(dataType)) && this.tracedDatagramGaps++ < MAX_TRACED_DATAGRAM_GAPS)
16883
17109
  this.trace({ phase: "datagram-gap", dataType });
16884
17110
  this.pendingByDataType.delete(dataType);
17111
+ if (dataType === P2PDataType.VIDEO)
17112
+ this.emit("videoGap");
16885
17113
  const last = this.lastSeqByType.get(dataType);
16886
17114
  const earliest = [...held.keys()].sort((a, b) => (a - last & 65535) - (b - last & 65535))[0];
16887
17115
  this.lastSeqByType.set(dataType, earliest - 1 & 65535);
@@ -16900,32 +17128,35 @@ var P2PSession = class _P2PSession extends EventEmitter2 {
16900
17128
  * Frames are packed back to back, so a frame header can itself be cut by a datagram boundary. The start
16901
17129
  * of a header left at the end of a datagram is carried into the next one rather than discarded; dropping
16902
17130
  * it would lose that frame and every frame after it until a datagram happened to begin on a header.
17131
+ * Payload fragments retain their original slices and are copied once, when the complete frame is delivered.
16903
17132
  */
16904
17133
  reassemble(dataType, datagramBody) {
16905
17134
  const pending = this.pendingByDataType.get(dataType);
16906
- let body = pending ? Buffer.concat([pending.buf, datagramBody]) : datagramBody;
16907
- const carryHeader = pending?.header;
16908
17135
  this.pendingByDataType.delete(dataType);
16909
- if (carryHeader) {
16910
- if (body.length < carryHeader.bytesToRead) {
16911
- this.pendingByDataType.set(dataType, { header: carryHeader, buf: body });
17136
+ let body = pending && !pending.header ? Buffer.concat([...pending.chunks, datagramBody]) : datagramBody;
17137
+ if (pending?.header) {
17138
+ const taken = Math.min(pending.header.bytesToRead - pending.byteLength, body.length);
17139
+ pending.chunks.push(body.subarray(0, taken));
17140
+ pending.byteLength += taken;
17141
+ body = body.subarray(taken);
17142
+ if (pending.byteLength < pending.header.bytesToRead) {
17143
+ this.pendingByDataType.set(dataType, pending);
16912
17144
  return;
16913
17145
  }
16914
- this.handleFrame(carryHeader, body.subarray(0, carryHeader.bytesToRead), dataType);
16915
- body = body.subarray(carryHeader.bytesToRead);
17146
+ this.handleFrame(pending.header, Buffer.concat(pending.chunks, pending.byteLength), dataType);
16916
17147
  }
16917
17148
  while (body.length >= P2P_DATA_HEADER_BYTES && body.subarray(0, 4).toString() === MAGIC_WORD) {
16918
17149
  const header = parseDataFrameHeader(body);
16919
17150
  const payload = body.subarray(P2P_DATA_HEADER_BYTES);
16920
17151
  if (payload.length < header.bytesToRead) {
16921
- this.pendingByDataType.set(dataType, { header, buf: payload });
17152
+ this.pendingByDataType.set(dataType, { header, chunks: [payload], byteLength: payload.length });
16922
17153
  return;
16923
17154
  }
16924
17155
  this.handleFrame(header, payload.subarray(0, header.bytesToRead), dataType);
16925
17156
  body = body.subarray(P2P_DATA_HEADER_BYTES + header.bytesToRead);
16926
17157
  }
16927
17158
  if (body.length > 0 && body.length < P2P_DATA_HEADER_BYTES && MAGIC_WORD.startsWith(body.subarray(0, 4).toString())) {
16928
- this.pendingByDataType.set(dataType, { buf: body });
17159
+ this.pendingByDataType.set(dataType, { chunks: [body], byteLength: body.length });
16929
17160
  }
16930
17161
  }
16931
17162
  /**
@@ -17518,7 +17749,8 @@ var AccessUnitAssembler = class {
17518
17749
  * `decode` extracts the payload of a frame, whatever the stream's encryption: it is called for EVERY
17519
17750
  * frame, including a continuation, because a continuation carries its own wrapped key ahead of its share
17520
17751
  * of the payload (measured: 129 bytes beyond what its header declares, exactly as a unit's first frame
17521
- * carries).
17752
+ * carries). A continuation without its matching open unit has no Annex-B start code and cannot be emitted
17753
+ * as a complete unit, even if its repeated header says keyframe.
17522
17754
  */
17523
17755
  push(payload, decode) {
17524
17756
  const header = parseVideoFrameHeader(payload);
@@ -17538,6 +17770,8 @@ var AccessUnitAssembler = class {
17538
17770
  return [unitOf(open2.header, Buffer.concat(open2.chunks))];
17539
17771
  }
17540
17772
  this.discard();
17773
+ if (!beginsAccessUnit(body))
17774
+ return [];
17541
17775
  if (full) {
17542
17776
  this.open = { header, chunks: [body], carried: body.length };
17543
17777
  return [];
@@ -17563,7 +17797,13 @@ function beginsAccessUnit(body) {
17563
17797
  return body[2] === 1 || body[2] === 0 && body[3] === 1;
17564
17798
  }
17565
17799
  function unitOf(header, data) {
17566
- return { keyframe: header.keyframe, width: header.width, height: header.height, data };
17800
+ return {
17801
+ sourceTimestamp: header.timestamp,
17802
+ keyframe: header.keyframe,
17803
+ width: header.width,
17804
+ height: header.height,
17805
+ data
17806
+ };
17567
17807
  }
17568
17808
 
17569
17809
  // dist/transport/p2p/annexb.js
@@ -17666,6 +17906,18 @@ function startCodeBegin(buf, payloadOffset) {
17666
17906
  return threeByte - 1;
17667
17907
  return threeByte;
17668
17908
  }
17909
+ function hasIdr(buf, codec) {
17910
+ for (const p of nalStarts(buf)) {
17911
+ const b = buf[p];
17912
+ if (codec === "h265") {
17913
+ const t = b >> 1 & 63;
17914
+ if (t === 19 || t === 20)
17915
+ return true;
17916
+ } else if ((b & 31) === 5)
17917
+ return true;
17918
+ }
17919
+ return false;
17920
+ }
17669
17921
  var MAX_CODED_DIMENSION = 32768;
17670
17922
  var H264_CHROMA_PROFILES = /* @__PURE__ */ new Set([100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135, 144]);
17671
17923
  var CHROMA_SUBSAMPLING = {
@@ -17878,6 +18130,7 @@ var AUDIO_HEADER_LEN = 16;
17878
18130
  var AUDIO_TYPE_OFFSET = 5;
17879
18131
  var SC4 = Buffer.from([0, 0, 0, 1]);
17880
18132
  var SC3 = Buffer.from([0, 0, 1]);
18133
+ var AAC_ELD_AUDIO_SPECIFIC_CONFIG = Buffer.from("f8f03000", "hex");
17881
18134
  var AUDIO_CODECS = { 0: "aac-lc", 2: "g711a", 7: "aac-eld" };
17882
18135
  var MAX_TRACED_DECODE_FAILURES = 3;
17883
18136
  var DEFAULT_KEEPALIVE_MS = 3e3;
@@ -17891,6 +18144,12 @@ var LiveStream = class extends EventEmitter3 {
17891
18144
  lastCodec = "h264";
17892
18145
  /** Rebuilds an access unit the station split across several frames — see {@link AccessUnitAssembler}. */
17893
18146
  units = new AccessUnitAssembler((drop) => this.reportDroppedUnit(drop));
18147
+ /** Whether a missing video datagram or incomplete unit invalidated the current reference chain. */
18148
+ awaitingKeyframeAfterGap = false;
18149
+ videoGapHandler = () => {
18150
+ this.units.discard();
18151
+ this.awaitingKeyframeAfterGap = true;
18152
+ };
17894
18153
  /** The channel inbound media must be tagged with, once {@link acceptsMedia} trusts the station's tag. */
17895
18154
  mediaChannel;
17896
18155
  tracedFirstVideoCommand = false;
@@ -17933,6 +18192,7 @@ var LiveStream = class extends EventEmitter3 {
17933
18192
  return this;
17934
18193
  this.listening = true;
17935
18194
  this.session.on("data", this.handler);
18195
+ this.session.on("videoGap", this.videoGapHandler);
17936
18196
  this.session.on("liveStartUnacknowledged", this.unackedHandler);
17937
18197
  this.sendStart();
17938
18198
  const keepAliveMs = this.opts.keepAliveMs ?? DEFAULT_KEEPALIVE_MS;
@@ -18030,6 +18290,8 @@ var LiveStream = class extends EventEmitter3 {
18030
18290
  return;
18031
18291
  this.listening = false;
18032
18292
  this.session.off("data", this.handler);
18293
+ this.session.off("videoGap", this.videoGapHandler);
18294
+ this.awaitingKeyframeAfterGap = false;
18033
18295
  this.session.off("liveStartUnacknowledged", this.unackedHandler);
18034
18296
  if (this.kaTimer)
18035
18297
  clearInterval(this.kaTimer);
@@ -18065,6 +18327,11 @@ var LiveStream = class extends EventEmitter3 {
18065
18327
  try {
18066
18328
  if (f.commandId === CMD_VIDEO_FRAME2) {
18067
18329
  for (const unit of this.units.push(f.data, (payload) => this.annexbOf(payload, f.signCode))) {
18330
+ if (this.awaitingKeyframeAfterGap) {
18331
+ if (!unit.keyframe)
18332
+ continue;
18333
+ this.awaitingKeyframeAfterGap = false;
18334
+ }
18068
18335
  if (!this.tracedFirstVideoUnit) {
18069
18336
  this.tracedFirstVideoUnit = true;
18070
18337
  this.trace({ phase: "first-video-unit", keyframe: unit.keyframe });
@@ -18077,6 +18344,7 @@ var LiveStream = class extends EventEmitter3 {
18077
18344
  this.lastCodec = sniffAnnexbCodec(unit.data) ?? this.lastCodec;
18078
18345
  this.settleKeepalive();
18079
18346
  this.emit("video", {
18347
+ sourceTimestamp: unit.sourceTimestamp,
18080
18348
  keyframe: unit.keyframe,
18081
18349
  width: unit.width,
18082
18350
  height: unit.height,
@@ -18092,7 +18360,7 @@ var LiveStream = class extends EventEmitter3 {
18092
18360
  if (!codec) {
18093
18361
  this.logger.debug(`[live] dropping audio frame: unknown codec id ${codecId ?? "missing"}`);
18094
18362
  } else {
18095
- this.emit("audio", { codec, data: audio });
18363
+ this.emit("audio", codec === "aac-eld" ? { codec, data: audio, config: AAC_ELD_AUDIO_SPECIFIC_CONFIG } : { codec, data: audio });
18096
18364
  }
18097
18365
  }
18098
18366
  }
@@ -18159,6 +18427,7 @@ var LiveStream = class extends EventEmitter3 {
18159
18427
  * otherwise silent in both directions: no frame reaches a consumer, and nothing states why.
18160
18428
  */
18161
18429
  reportDroppedUnit(drop) {
18430
+ this.awaitingKeyframeAfterGap = true;
18162
18431
  const message = `[live] dropped an incomplete access unit (${drop.carried} bytes in ${drop.chunks} frame(s), tail never arrived, ${drop.count} so far)`;
18163
18432
  if (drop.count === 1)
18164
18433
  this.logger.warn(message);
@@ -18572,9 +18841,11 @@ function decodeRecording(frames, eccPrivateKeyHex) {
18572
18841
  if (eccPrivateKey.length !== 32)
18573
18842
  throw new RecordingDownloadError("undecodable", "the cipher key is not a P-256 key");
18574
18843
  const decoder = new VideoFrameDecoder(eccPrivateKey);
18844
+ const assembler = new AccessUnitAssembler();
18575
18845
  const video = [];
18576
18846
  const audio = [];
18577
18847
  const numbers = /* @__PURE__ */ new Set();
18848
+ const receivedNumbers = /* @__PURE__ */ new Set();
18578
18849
  let firstStamp;
18579
18850
  let lastStamp;
18580
18851
  for (const { commandId, raw } of frames) {
@@ -18582,14 +18853,15 @@ function decodeRecording(frames, eccPrivateKeyHex) {
18582
18853
  const header = parseVideoFrameHeader(raw);
18583
18854
  if (!header)
18584
18855
  continue;
18585
- const h264 = header.keyframe ? decoder.decodeFrame(raw)?.h264 : raw.length >= VIDEO_HEADER_LEN2 + header.payloadLength ? raw.subarray(VIDEO_HEADER_LEN2, VIDEO_HEADER_LEN2 + header.payloadLength) : void 0;
18586
- if (!h264?.length)
18587
- continue;
18588
- video.push(h264);
18589
- numbers.add(header.sequence);
18590
- const stamp = raw.readUIntLE(14, 6);
18591
- firstStamp ??= stamp;
18592
- lastStamp = stamp;
18856
+ receivedNumbers.add(header.sequence);
18857
+ const units = assembler.push(raw, (payload) => header.keyframe ? decoder.decodeFrame(payload)?.h264 : payload.length >= VIDEO_HEADER_LEN2 + header.payloadLength ? payload.subarray(VIDEO_HEADER_LEN2, VIDEO_HEADER_LEN2 + header.payloadLength) : void 0);
18858
+ for (const unit of units) {
18859
+ video.push(unit.data);
18860
+ numbers.add(header.sequence);
18861
+ const stamp = raw.readUIntLE(14, 6);
18862
+ firstStamp ??= stamp;
18863
+ lastStamp = stamp;
18864
+ }
18593
18865
  } else if (commandId === CommandType.CMD_AUDIO_FRAME) {
18594
18866
  const mediaKey = decoder.currentMediaKey;
18595
18867
  if (!mediaKey || raw.length < AUDIO_BODY_START || raw[5] !== AUDIO_CODEC_AAC_LC)
@@ -18605,9 +18877,10 @@ function decodeRecording(frames, eccPrivateKeyHex) {
18605
18877
  if (!video.length)
18606
18878
  throw new RecordingDownloadError("undecodable", "no video frame of the recording decoded");
18607
18879
  const ordered = [...numbers];
18608
- let missingFrames = 0;
18609
- for (let i = 1; i < ordered.length; i++) {
18610
- const step = ordered[i] - ordered[i - 1] & 65535;
18880
+ const received = [...receivedNumbers];
18881
+ let missingFrames = receivedNumbers.size - numbers.size;
18882
+ for (let i = 1; i < received.length; i++) {
18883
+ const step = received[i] - received[i - 1] & 65535;
18611
18884
  if (step > 1 && step < 32768)
18612
18885
  missingFrames += step - 1;
18613
18886
  }
@@ -19415,6 +19688,14 @@ var SharedLiveSource = class {
19415
19688
  this.opts.onIdle?.();
19416
19689
  }
19417
19690
  };
19691
+ function attachUnlessAborted(source, signal) {
19692
+ const consumer = source.attach();
19693
+ if (signal?.aborted) {
19694
+ consumer.detach();
19695
+ signal.throwIfAborted();
19696
+ }
19697
+ return consumer;
19698
+ }
19418
19699
 
19419
19700
  // dist/transport/p2p/session-manager.js
19420
19701
  var SessionSupersededError = class extends Error {
@@ -19828,7 +20109,8 @@ var AdtsFrameReader = class {
19828
20109
  };
19829
20110
 
19830
20111
  // dist/transport/p2p/talkback.js
19831
- var DEFAULT_HIGH_WATER_FRAMES = Math.ceil(2e3 / AAC_FRAME_MS);
20112
+ var HIGH_WATER_MS = 2e3;
20113
+ var TALKBACK_ELD_FRAME_MS = 32;
19832
20114
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
19833
20115
  var Talkback = class extends EventEmitter5 {
19834
20116
  sink;
@@ -19836,7 +20118,8 @@ var Talkback = class extends EventEmitter5 {
19836
20118
  reader = new AdtsFrameReader();
19837
20119
  queue = [];
19838
20120
  logger;
19839
- highWater;
20121
+ /** Playback duration of one queued frame, the pacer's step: 64 ms for `aac-lc`, 32 ms for `aac-eld`. */
20122
+ frameMs = AAC_FRAME_MS;
19840
20123
  idleTimeoutMs;
19841
20124
  timer;
19842
20125
  started = false;
@@ -19862,9 +20145,14 @@ var Talkback = class extends EventEmitter5 {
19862
20145
  this.sink = sink;
19863
20146
  this.opts = opts;
19864
20147
  this.logger = opts.logger ?? noopLogger;
19865
- this.highWater = opts.highWaterFrames ?? DEFAULT_HIGH_WATER_FRAMES;
19866
20148
  this.idleTimeoutMs = opts.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
19867
20149
  }
20150
+ /** Frames the pacing queue holds before a writable applies backpressure: {@link HIGH_WATER_MS} of this codec. */
20151
+ get highWater() {
20152
+ return this.opts.highWaterFrames ?? Math.ceil(HIGH_WATER_MS / this.frameMs);
20153
+ }
20154
+ /** The codec this talkback sends, set by {@link start}. */
20155
+ codec = "aac-lc";
19868
20156
  /** Frames still queued for the wire. */
19869
20157
  get pending() {
19870
20158
  return this.queue.length;
@@ -19873,25 +20161,33 @@ var Talkback = class extends EventEmitter5 {
19873
20161
  * Open the device's talkback path and begin the pacing tick. Throws when the topology's control
19874
20162
  * frame could not be sent — for a HomeBase-attached camera that means the level-2 key was never
19875
20163
  * negotiated, which would otherwise leave a silent session that accepts audio nobody hears.
20164
+ *
20165
+ * `codec` is the codec the camera's speaker plays; it fixes the input this talkback accepts and the pacing step.
19876
20166
  */
19877
- start() {
20167
+ start(codec) {
19878
20168
  if (this.started)
19879
20169
  return this;
20170
+ if (codec === "aac-eld" && this.opts.encoder) {
20171
+ throw new Error("talkback: this camera plays aac-eld; an AacEncoder produces aac-lc");
20172
+ }
20173
+ this.codec = codec;
20174
+ this.frameMs = codec === "aac-eld" ? TALKBACK_ELD_FRAME_MS : AAC_FRAME_MS;
19880
20175
  if (!this.sink.startTalkback(this.opts.channel, this.opts.homeBaseAttached)) {
19881
20176
  throw new Error(`talkback: could not open the audio path on channel ${this.opts.channel}`);
19882
20177
  }
19883
20178
  this.started = true;
19884
20179
  const now2 = Date.now();
19885
- this.nextDueAt = now2 + AAC_FRAME_MS;
20180
+ this.nextDueAt = now2 + this.frameMs;
19886
20181
  this.lastWriteAt = now2;
19887
- this.timer = setInterval(() => this.tick(), AAC_FRAME_MS);
20182
+ this.timer = setInterval(() => this.tick(), this.frameMs);
19888
20183
  this.timer.unref?.();
19889
20184
  this.sink.on?.("audioGap", this.onAudioGap);
19890
20185
  return this;
19891
20186
  }
19892
20187
  /**
19893
- * Queue audio. Bytes are ADTS AAC, or PCM when an encoder was supplied; either way the input is
19894
- * treated as a stream, so a chunk carrying part of a frame is held until the rest arrives.
20188
+ * Queue audio in the codec this talkback sends. For `aac-lc` the bytes are ADTS, or PCM when an encoder was
20189
+ * supplied, read as a stream, so a chunk carrying part of a frame is held until the rest arrives. For `aac-eld`
20190
+ * each call is one whole access unit; a unit over the device's length limit is dropped with an `error`.
19895
20191
  *
19896
20192
  * Audio written after {@link end} is dropped with an `error` rather than queued: `finished` has
19897
20193
  * either already fired or is owed on the frames written before it, so a late chunk would either play
@@ -19905,6 +20201,15 @@ var Talkback = class extends EventEmitter5 {
19905
20201
  return;
19906
20202
  }
19907
20203
  this.lastWriteAt = Date.now();
20204
+ if (this.codec === "aac-eld") {
20205
+ if (chunk.length > MAX_AUDIO_FRAME_BYTES) {
20206
+ this.fail(new Error(`talkback: frame of ${chunk.length} B exceeds the device's ${MAX_AUDIO_FRAME_BYTES} B limit`));
20207
+ return;
20208
+ }
20209
+ if (chunk.length)
20210
+ this.queue.push(chunk);
20211
+ return;
20212
+ }
19908
20213
  if (!this.opts.encoder) {
19909
20214
  this.enqueue(this.reader.push(chunk));
19910
20215
  return;
@@ -19973,14 +20278,14 @@ var Talkback = class extends EventEmitter5 {
19973
20278
  return;
19974
20279
  const now2 = Date.now();
19975
20280
  if (!this.queue.length) {
19976
- this.nextDueAt = now2 + AAC_FRAME_MS;
20281
+ this.nextDueAt = now2 + this.frameMs;
19977
20282
  this.idleCheck(now2);
19978
20283
  this.announceFinishIfDone();
19979
20284
  return;
19980
20285
  }
19981
20286
  while (this.queue.length && now2 >= this.nextDueAt) {
19982
20287
  const frame = this.queue.shift();
19983
- this.nextDueAt += AAC_FRAME_MS;
20288
+ this.nextDueAt += this.frameMs;
19984
20289
  try {
19985
20290
  this.sink.sendAudioFrame(this.opts.channel, frame);
19986
20291
  } catch (e) {
@@ -20038,9 +20343,11 @@ var Talkback = class extends EventEmitter5 {
20038
20343
  /**
20039
20344
  * A Writable over {@link write} that withholds its callback while the queue is at the high-water
20040
20345
  * mark — which is what turns `pipe()` from a file into playback at speed rather than a memory spike.
20346
+ * For `aac-eld` it is object-mode: each write is one access unit.
20041
20347
  */
20042
20348
  writable() {
20043
20349
  return new Writable({
20350
+ objectMode: this.codec === "aac-eld",
20044
20351
  write: (chunk, _enc, cb) => {
20045
20352
  this.write(chunk);
20046
20353
  if (this.queue.length < this.highWater)
@@ -20109,7 +20416,7 @@ var CODEC_BOXES = {
20109
20416
  h264: { sample: "avc1", config: "avcC" },
20110
20417
  h265: { sample: "hvc1", config: "hvcC" }
20111
20418
  };
20112
- var AAC_ELD_SAMPLES_PER_FRAME = 512;
20419
+ var AAC_ELD_SAMPLES_PER_FRAME = 480;
20113
20420
  var ADTS_FREQUENCY_INDEX_16K = 8;
20114
20421
  var ADTS_CHANNELS_MONO = 1;
20115
20422
  var Fmp4Muxer = class {
@@ -20124,9 +20431,12 @@ var Fmp4Muxer = class {
20124
20431
  fragTicks = 0;
20125
20432
  // ticks accumulated in the open fragment
20126
20433
  samples = [];
20127
- lastVideoTimestampMs;
20434
+ /** Ticks from the first video sample's start to the newest sample's end, at its provisional duration. */
20435
+ videoTicks = 0;
20128
20436
  audioRequested;
20129
20437
  audioCodec;
20438
+ /** Decoder config of an AAC-ELD track, taken from its frames; absent for AAC-LC, whose `esds` config is fixed. */
20439
+ audioConfig;
20130
20440
  audioDisabled = false;
20131
20441
  audioSamples = [];
20132
20442
  audioBaseDecodeTime = 0;
@@ -20146,6 +20456,10 @@ var Fmp4Muxer = class {
20146
20456
  * Push one access unit. Returns any completed segments: the `init` on the first keyframe, and/or a
20147
20457
  * media fragment when this frame closed the open one. Returns `undefined` if nothing is emitted yet
20148
20458
  * (e.g. delta frames before the first keyframe).
20459
+ *
20460
+ * A sample lasts until the next frame's `timestampMs`, measured from the first keyframe's, so the video
20461
+ * timeline follows the arrival clock; a frame that shares the previous one's timestamp leaves that
20462
+ * sample one tick long, and the next frame's duration absorbs the difference.
20149
20463
  */
20150
20464
  push(frame, timestampMs = now()) {
20151
20465
  if (frame.codec === "av1")
@@ -20164,15 +20478,14 @@ var Fmp4Muxer = class {
20164
20478
  this.height = declared?.height ?? frame.height;
20165
20479
  this.firstVideoTimestampMs = timestampMs;
20166
20480
  }
20167
- if (this.lastVideoTimestampMs !== void 0 && this.samples.length) {
20168
- const measured = Math.round((timestampMs - this.lastVideoTimestampMs) * (TIMESCALE / 1e3));
20169
- if (measured > 0) {
20170
- const previous = this.samples[this.samples.length - 1];
20171
- this.fragTicks += measured - previous.duration;
20172
- previous.duration = measured;
20173
- }
20481
+ if (this.firstVideoTimestampMs !== void 0 && this.samples.length) {
20482
+ const previous = this.samples[this.samples.length - 1];
20483
+ const arrival = Math.round((timestampMs - this.firstVideoTimestampMs) * (TIMESCALE / 1e3));
20484
+ const duration = Math.max(1, arrival - (this.videoTicks - previous.duration));
20485
+ this.fragTicks += duration - previous.duration;
20486
+ this.videoTicks += duration - previous.duration;
20487
+ previous.duration = duration;
20174
20488
  }
20175
- this.lastVideoTimestampMs = timestampMs;
20176
20489
  let fragment;
20177
20490
  if (frame.keyframe && this.samples.length > 0 && this.fragTicks >= this.fragmentTicks) {
20178
20491
  if (!this.initSent) {
@@ -20184,6 +20497,7 @@ var Fmp4Muxer = class {
20184
20497
  }
20185
20498
  this.samples.push({ data: annexbToAvcc(frame.data), duration: this.firstDuration, keyframe: frame.keyframe });
20186
20499
  this.fragTicks += this.firstDuration;
20500
+ this.videoTicks += this.firstDuration;
20187
20501
  if (!this.initSent && (!this.audioRequested || this.audioCodec || this.audioDisabled)) {
20188
20502
  init = this.buildInit();
20189
20503
  this.initSent = true;
@@ -20193,7 +20507,10 @@ var Fmp4Muxer = class {
20193
20507
  }
20194
20508
  return void 0;
20195
20509
  }
20196
- /** Add one station-declared AAC access unit to the audio track. G.711 remains available via `live()`. */
20510
+ /**
20511
+ * Add one station-declared AAC access unit to the audio track: an ADTS frame for AAC-LC, a raw access unit
20512
+ * described by its frame's config for AAC-ELD. G.711 remains available via `live()`.
20513
+ */
20197
20514
  pushAudio(frame, timestampMs = now()) {
20198
20515
  if (!this.audioRequested || this.audioDisabled)
20199
20516
  return void 0;
@@ -20209,12 +20526,19 @@ var Fmp4Muxer = class {
20209
20526
  if (this.audioCodec && this.audioCodec !== frame.codec) {
20210
20527
  return this.disableAudio();
20211
20528
  }
20212
- const header = parseAdtsHeader(frame.data);
20213
- if (!header || header.frameLength > frame.data.length) {
20214
- throw new Error(`fMP4 muxer: ${frame.codec} frame is not a complete ADTS access unit`);
20215
- }
20216
- if (header.frequencyIndex !== ADTS_FREQUENCY_INDEX_16K || header.channels !== ADTS_CHANNELS_MONO) {
20217
- return this.disableAudio();
20529
+ let sample;
20530
+ if (frame.codec === "aac-eld") {
20531
+ this.audioConfig = frame.config;
20532
+ sample = frame.data;
20533
+ } else {
20534
+ const header = parseAdtsHeader(frame.data);
20535
+ if (!header || header.frameLength > frame.data.length) {
20536
+ throw new Error(`fMP4 muxer: ${frame.codec} frame is not a complete ADTS access unit`);
20537
+ }
20538
+ if (header.frequencyIndex !== ADTS_FREQUENCY_INDEX_16K || header.channels !== ADTS_CHANNELS_MONO) {
20539
+ return this.disableAudio();
20540
+ }
20541
+ sample = frame.data.subarray(header.headerLength, header.frameLength);
20218
20542
  }
20219
20543
  this.audioCodec = frame.codec;
20220
20544
  this.firstAudioTimestampMs ??= timestampMs;
@@ -20226,7 +20550,7 @@ var Fmp4Muxer = class {
20226
20550
  this.audioSamples[this.audioSamples.length - 1].duration = measured;
20227
20551
  }
20228
20552
  this.audioSamples.push({
20229
- data: frame.data.subarray(header.headerLength, header.frameLength),
20553
+ data: sample,
20230
20554
  duration: frame.codec === "aac-eld" ? AAC_ELD_SAMPLES_PER_FRAME : AAC_SAMPLES_PER_FRAME,
20231
20555
  keyframe: true
20232
20556
  });
@@ -20499,7 +20823,7 @@ var Fmp4Muxer = class {
20499
20823
  return box("mp4a", head, this.esds());
20500
20824
  }
20501
20825
  esds() {
20502
- const config = this.audioCodec === "aac-eld" ? Buffer.from([248, 240, 32]) : Buffer.from([20, 8]);
20826
+ const config = this.audioConfig ?? Buffer.from([20, 8]);
20503
20827
  const specific = descriptor(5, config);
20504
20828
  const decoder = descriptor(4, Buffer.concat([Buffer.from([64, 21, 0, 0, 0]), u32(64e3), u32(32e3), specific]));
20505
20829
  const sl = descriptor(6, Buffer.from([2]));
@@ -20704,16 +21028,12 @@ function stationOf(dev) {
20704
21028
  const parent = typeof raw.parent_sn === "string" && raw.parent_sn && raw.parent_sn !== dev.sn ? raw.parent_sn : void 0;
20705
21029
  return parent ?? dev.stationSn ?? resolvedStationSn(raw, dev.sn);
20706
21030
  }
20707
- function statedChannel(dev) {
20708
- const v = dev.raw?.device_channel;
20709
- return typeof v === "number" ? v : void 0;
20710
- }
20711
21031
  function stationChannels(devices) {
20712
21032
  const out = /* @__PURE__ */ new Map();
20713
21033
  const claimants = /* @__PURE__ */ new Map();
20714
21034
  for (const d of devices) {
20715
21035
  const station = stationOf(d);
20716
- const stated = statedChannel(d);
21036
+ const stated = d.channel;
20717
21037
  if (d.sn === station || stated === void 0)
20718
21038
  continue;
20719
21039
  const counts = claimants.get(station) ?? /* @__PURE__ */ new Map();
@@ -20722,7 +21042,7 @@ function stationChannels(devices) {
20722
21042
  }
20723
21043
  for (const d of devices) {
20724
21044
  const station = stationOf(d);
20725
- const stated = statedChannel(d);
21045
+ const stated = d.channel;
20726
21046
  if (d.sn === station)
20727
21047
  out.set(d.sn, { channel: stated ?? 0 });
20728
21048
  else if (stated === void 0)
@@ -20737,17 +21057,6 @@ function stationChannels(devices) {
20737
21057
 
20738
21058
  // dist/transport/p2p/command-router.js
20739
21059
  var DIRECT_CMD_SENDS = 5;
20740
- function abortable(work, signal) {
20741
- if (!signal)
20742
- return work;
20743
- signal.throwIfAborted();
20744
- return Promise.race([
20745
- work,
20746
- new Promise((_resolve, reject) => {
20747
- signal.addEventListener("abort", () => reject(signal.reason), { once: true });
20748
- })
20749
- ]);
20750
- }
20751
21060
  var LEVEL2_GRACE_MS = 25e3;
20752
21061
  var LEVEL2_SETTLE_MS = 8e3;
20753
21062
  var P2P_STATION_WAITS = {
@@ -20756,6 +21065,30 @@ var P2P_STATION_WAITS = {
20756
21065
  level2Settle: LEVEL2_SETTLE_MS
20757
21066
  };
20758
21067
  var RTSP_URL_READ_TIMEOUT_MS = 12e3;
21068
+ var TALKBACK_CODEC_WAIT_MS = 3e3;
21069
+ var ELD_TALKBACK_MODELS = /* @__PURE__ */ new Set(["T8410C"]);
21070
+ function speakerCodec(consumer, talk, timeoutMs) {
21071
+ return new Promise((resolve) => {
21072
+ let timer;
21073
+ const settle = (codec) => {
21074
+ clearTimeout(timer);
21075
+ consumer.off("video", onVideo);
21076
+ consumer.off("audio", onAudio);
21077
+ consumer.off("stop", onStop);
21078
+ talk.off("stop", onStop);
21079
+ resolve(codec);
21080
+ };
21081
+ const onVideo = () => {
21082
+ timer ??= setTimeout(() => settle("aac-lc"), timeoutMs);
21083
+ };
21084
+ const onAudio = (frame) => settle(frame.codec === "aac-eld" ? "aac-eld" : "aac-lc");
21085
+ const onStop = () => settle("aac-lc");
21086
+ consumer.on("video", onVideo);
21087
+ consumer.on("audio", onAudio);
21088
+ consumer.on("stop", onStop);
21089
+ talk.once("stop", onStop);
21090
+ });
21091
+ }
20759
21092
  var SHARED_LIVE_OPT_KEYS = [
20760
21093
  "eccPrivateKey",
20761
21094
  "keepAliveMs",
@@ -21174,14 +21507,20 @@ var P2PCommandRouter = class _P2PCommandRouter {
21174
21507
  }
21175
21508
  }
21176
21509
  /**
21177
- * Restart a HomeBase. `RESTART_HUB` (1034) is a station-scalar on the broadcast channel 255: a
21178
- * level-2 frame whose body is `[u32 value][account_id padded]` — the same shape as the hub
21179
- * alarm-volume control. ✅ Wire-confirmed byte-exact from a capture of the app's own Restart
21180
- * (2026-08-03) and HW-tested: the captured frame carried value `0` and rebooted the hub. Replays
21181
- * like every other level-2 control, so a single dropped datagram doesn't lose it.
21510
+ * Restart the station that owns `sn`'s P2P session. `RESTART_HUB` (1034) is a station-scalar on the
21511
+ * broadcast channel 255 whose body is `[u32 value][account_id padded]`, value `0`. ✅ Wire-confirmed
21512
+ * byte-exact as a level-2 frame from a capture of the app's own HomeBase Restart (2026-08-03).
21513
+ *
21514
+ * The seal follows the session, as {@link sendBySessionLevel} defines it: a keyed session takes the
21515
+ * level-2 frame, a keyless one — a standalone camera, which never negotiates a key — the same body
21516
+ * sealed level-1. Both are replayed {@link DIRECT_CMD_SENDS}× at 200ms, as every other unacknowledged
21517
+ * control here is.
21182
21518
  */
21183
21519
  async rebootStation(sn) {
21184
- await this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel2Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB, 8));
21520
+ await this.sendBySessionLevel(sn, {
21521
+ l2: (resolved) => this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel2Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB, 8), resolved),
21522
+ l1: (resolved) => this.replayLevel2Send(sn, `reboot ${sn}`, ({ session, accountId }) => session.sendRawLevel1Bytes(buildDirectBinaryBody(0, accountId), 255, P2P_ENVELOPE.RESTART_HUB), resolved)
21523
+ });
21185
21524
  }
21186
21525
  /**
21187
21526
  * A {@link MediaProvider} bound to one serial — resolves the session then calls `p2p/media`.
@@ -21209,11 +21548,11 @@ var P2PCommandRouter = class _P2PCommandRouter {
21209
21548
  },
21210
21549
  live: async (opts) => {
21211
21550
  const source = await this.sharedLiveSourceFor(sn, opts, true);
21212
- return this.attachUnlessAborted(source, opts?.signal);
21551
+ return attachUnlessAborted(source, opts?.signal);
21213
21552
  },
21214
21553
  openReadable: async (opts) => {
21215
21554
  const source = await this.sharedLiveSourceFor(sn, opts ?? {}, true);
21216
- return openReadableFromConsumer(this.attachUnlessAborted(source, opts?.signal), opts);
21555
+ return openReadableFromConsumer(attachUnlessAborted(source, opts?.signal), opts);
21217
21556
  },
21218
21557
  recordFragments: (opts) => this.recordFragments(sn, opts),
21219
21558
  talkback: (opts) => this.openTalkback(sn, opts),
@@ -21303,6 +21642,11 @@ var P2PCommandRouter = class _P2PCommandRouter {
21303
21642
  * stream costs nothing extra and a talkback on an otherwise idle camera opens the session it needs
21304
21643
  * instead of playing into silence.
21305
21644
  *
21645
+ * **On a model in {@link ELD_TALKBACK_MODELS}, the speaker plays the codec the camera sends.** So the first
21646
+ * audio frame of the media session this talkback holds decides its codec ({@link speakerCodec}), within
21647
+ * {@link TALKBACK_CODEC_WAIT_MS} of the session's first frame, and the claim is re-checked after that wait as
21648
+ * after the warm-up. Every other model opens `aac-lc` at once.
21649
+ *
21306
21650
  * The level-2 key is waited for softly: only the HomeBase-attached path requires it, and
21307
21651
  * {@link Talkback.start} reports that failure precisely, so a hard wait here would reject an
21308
21652
  * own-session camera that legitimately never negotiates one.
@@ -21372,7 +21716,11 @@ var P2PCommandRouter = class _P2PCommandRouter {
21372
21716
  consumer.on("stop", () => {
21373
21717
  void talk.stop().catch((e) => logger.warn?.(`talkback: stop for ${sn} failed: ${String(e)}`));
21374
21718
  });
21375
- return talk.start();
21719
+ const codec = ELD_TALKBACK_MODELS.has(this.recordFor(sn)?.model ?? "") ? await speakerCodec(consumer, talk, TALKBACK_CODEC_WAIT_MS) : "aac-lc";
21720
+ if (this.talkbacks.get(key) !== talk) {
21721
+ throw new Error(`talkback: ${sn} was closed while its speaker codec was being read`);
21722
+ }
21723
+ return talk.start(codec);
21376
21724
  } catch (e) {
21377
21725
  if (this.talkbacks.get(key) === talk)
21378
21726
  this.talkbacks.delete(key);
@@ -21572,22 +21920,6 @@ var P2PCommandRouter = class _P2PCommandRouter {
21572
21920
  * A still with no live sibling re-asserts, so a tile refreshing on a quiet station is
21573
21921
  * unaffected.
21574
21922
  */
21575
- /**
21576
- * Attach a consumer, unless the caller has already abandoned the call.
21577
- *
21578
- * The acquisition it just waited through can outlast the caller's interest, and a consumer attached for
21579
- * somebody who has gone keeps the pull warm for nobody. Detaching immediately gives the pull back, which
21580
- * lets it linger and fall away if this was the only thing holding it, and leaves it untouched if it was
21581
- * not.
21582
- */
21583
- attachUnlessAborted(source, signal) {
21584
- const consumer = source.attach();
21585
- if (signal?.aborted) {
21586
- consumer.detach();
21587
- signal.throwIfAborted();
21588
- }
21589
- return consumer;
21590
- }
21591
21923
  /**
21592
21924
  * Dispose one cached live source and forget it, so the next acquisition builds a fresh one. Its claim
21593
21925
  * on a session goes with it, and a media session opened for this source alone is closed: nothing else
@@ -22085,7 +22417,7 @@ var P2PCommandRouter = class _P2PCommandRouter {
22085
22417
  * **`set-json-raw` intent** — bare JSON, no envelope: outer P2P cmd = `outerCmd` itself, plaintext
22086
22418
  * exactly `{account_id,...data}` (`session.sendRawLevel2` with no wrapper). Reversed from a live
22087
22419
  * capture of the app's own SET_SNOOZE_TIME (1271) frame — see `param-dictionary.ts`'s `1271` entry
22088
- * (`snoozeTime`); the alarm-delay config (1255, `arming.ts`'s `ARMING_CMD.ALARM_DELAY_CONFIG`) reuses
22420
+ * (`snoozeTime`); the alarm-delay config (1255, `arming.ts`'s `ARMING_CMD.SET_ALL_ACTION`) reuses
22089
22421
  * the same bare-JSON shape.
22090
22422
  */
22091
22423
  async sendJsonRaw(sn, outerCmd, data, channel) {
@@ -22357,98 +22689,1630 @@ var P2PCommandRouter = class _P2PCommandRouter {
22357
22689
  }
22358
22690
  };
22359
22691
 
22360
- // dist/transport/mqtt/command-router.js
22361
- import { randomBytes as randomBytes3 } from "node:crypto";
22692
+ // dist/transport/rtc/live.js
22693
+ import { EventEmitter as EventEmitter7 } from "node:events";
22362
22694
 
22363
- // dist/transport/mqtt/broker-discovery.js
22364
- import { resolve4 } from "node:dns/promises";
22365
- async function resolveBrokerIps(hostname) {
22695
+ // dist/transport/rtc/portal-packet.js
22696
+ var MAGIC2 = Buffer.from("XZYH", "ascii");
22697
+ var PORTAL_HEADER_LENGTH = 16;
22698
+ var PORTAL_CMD_SET_PAYLOAD = 1350;
22699
+ var PORTAL_STATION_CHANNEL = 255;
22700
+ var PortalLinkType = {
22701
+ /** Command channel: requests out, acknowledgements back. */
22702
+ COMMAND: 1,
22703
+ /** Station-originated frames: pushes, notify payloads, control results. */
22704
+ NOTIFY: 3,
22705
+ /** Live video. */
22706
+ LIVE: 5
22707
+ };
22708
+ function encodeLe(value, width) {
22709
+ const buf = Buffer.alloc(width);
22710
+ let v = value >>> 0;
22711
+ for (let i = 0; i < width; i++) {
22712
+ buf[i] = v & 255;
22713
+ v >>>= 8;
22714
+ }
22715
+ return buf;
22716
+ }
22717
+ function buildPortalHeader(commandId, paramLength, channel, segment, isResponse = 0, devType = 2) {
22718
+ const header = Buffer.alloc(PORTAL_HEADER_LENGTH);
22719
+ MAGIC2.copy(header, 0);
22720
+ encodeLe(commandId, 2).copy(header, 4);
22721
+ encodeLe(paramLength, 4).copy(header, 6);
22722
+ header[10] = 0;
22723
+ header[11] = segment & 255;
22724
+ header[12] = channel & 255;
22725
+ header[13] = 0;
22726
+ header[14] = isResponse & 255;
22727
+ header[15] = devType & 255;
22728
+ return header;
22729
+ }
22730
+ function parsePortalHeader(buf) {
22731
+ if (buf.length < PORTAL_HEADER_LENGTH || buf.subarray(0, 4).compare(MAGIC2) !== 0)
22732
+ return void 0;
22733
+ return {
22734
+ commandId: buf.readUInt16LE(4),
22735
+ paramLength: buf.readUInt32LE(6),
22736
+ segment: buf[11],
22737
+ channel: buf[12],
22738
+ isResponse: buf[14],
22739
+ devType: buf[15]
22740
+ };
22741
+ }
22742
+ function isPortalPacket(buf) {
22743
+ return buf.length >= PORTAL_HEADER_LENGTH && buf.subarray(0, 4).compare(MAGIC2) === 0;
22744
+ }
22745
+ function buildPortalPacket(req) {
22746
+ const body = Buffer.from(JSON.stringify(req.payload), "utf8");
22747
+ const header = buildPortalHeader(req.commandId, body.length, req.channel, req.segment, req.isResponse ?? 0, req.devType ?? 2);
22748
+ return Buffer.concat([header, body]);
22749
+ }
22750
+ function parseJsonBody(buf) {
22751
+ let text2 = buf.toString("utf8");
22752
+ while (text2.endsWith("\0"))
22753
+ text2 = text2.slice(0, -1);
22366
22754
  try {
22367
- return await resolve4(hostname);
22755
+ return JSON.parse(text2);
22368
22756
  } catch {
22369
- return [];
22757
+ return text2;
22370
22758
  }
22371
22759
  }
22372
- function mergeCandidateIps(dnsIps, extraIps = []) {
22373
- return Array.from(/* @__PURE__ */ new Set([...dnsIps, ...extraIps]));
22374
- }
22375
- function rankResults(results) {
22376
- return [...results].sort((a, b) => Number(b.granted) - Number(a.granted));
22377
- }
22378
- async function probeBrokerInstance(ip, creds, opts) {
22379
- const mqtt = await loadMqtt();
22380
- const start = Date.now();
22381
- const timeoutMs = opts.timeoutMs ?? 8e3;
22382
- return await new Promise((resolvePromise) => {
22383
- let settled = false;
22384
- const finish = (r) => {
22385
- if (settled)
22386
- return;
22387
- settled = true;
22388
- clearTimeout(timer);
22389
- try {
22390
- client.end(true);
22391
- } catch {
22392
- }
22393
- resolvePromise({ ip, ms: Date.now() - start, ...r });
22760
+ function parsePortalPacket(buf, linkType = PortalLinkType.COMMAND) {
22761
+ const header = parsePortalHeader(buf);
22762
+ if (!header)
22763
+ return void 0;
22764
+ const body = buf.subarray(PORTAL_HEADER_LENGTH, PORTAL_HEADER_LENGTH + header.paramLength);
22765
+ if (linkType === PortalLinkType.NOTIFY) {
22766
+ const data = parseJsonBody(body);
22767
+ const cmd = typeof data === "object" && data !== null && "cmd" in data ? Number(data.cmd) : void 0;
22768
+ return {
22769
+ commandId: header.commandId,
22770
+ channel: header.channel,
22771
+ segment: header.segment,
22772
+ isResponse: header.isResponse,
22773
+ linkType,
22774
+ cmd,
22775
+ data
22394
22776
  };
22395
- const client = mqtt.connect({
22396
- host: ip,
22397
- port: creds.port ?? 8883,
22398
- protocol: "mqtts",
22399
- ...bareIpTlsOptions({
22400
- hostname: creds.hostname,
22401
- cert: creds.certificate_pem,
22402
- key: creds.private_key,
22403
- ca: creds.aws_root_ca1_pem
22404
- }),
22405
- clientId: opts.clientId,
22406
- protocolVersion: 4,
22407
- keepalive: 60,
22408
- clean: true,
22409
- reconnectPeriod: 0,
22410
- connectTimeout: timeoutMs
22411
- });
22412
- const timer = setTimeout(() => finish({ granted: false, error: "timeout" }), timeoutMs);
22413
- client.on("connect", () => {
22414
- client.subscribe(opts.topic, { qos: 1 }, (err, granted) => {
22415
- if (err)
22416
- return finish({ granted: false, error: err.message });
22417
- const g = granted?.[0];
22418
- const denied = !g || g.qos === 128;
22419
- finish({ granted: !denied, grantedQos: g?.qos });
22420
- });
22421
- });
22422
- client.on("error", (err) => finish({ granted: false, error: err.message }));
22423
- });
22424
- }
22425
- async function discoverReachableInstance(creds, opts) {
22426
- const dnsIps = await resolveBrokerIps(creds.hostname);
22427
- const all = mergeCandidateIps(dnsIps, opts.candidateIps);
22428
- const results = [];
22429
- for (const ip of all) {
22430
- const r = await probeBrokerInstance(ip, creds, {
22431
- clientId: opts.clientIdFor(ip),
22432
- topic: opts.topic,
22433
- timeoutMs: opts.perAttemptTimeoutMs
22434
- });
22435
- results.push(r);
22436
- if (r.granted && opts.stopOnFirstGrant)
22437
- break;
22438
22777
  }
22439
- return rankResults(results);
22778
+ return {
22779
+ commandId: header.commandId,
22780
+ channel: header.channel,
22781
+ segment: header.segment,
22782
+ isResponse: header.isResponse,
22783
+ linkType,
22784
+ errCode: body.length >= 4 ? body.readInt32LE(0) : -1,
22785
+ data: body.length > 4 ? parseJsonBody(body.subarray(4)) : void 0
22786
+ };
22440
22787
  }
22441
-
22442
- // dist/transport/dp-preset.js
22443
- var RGBCW_CH = {
22444
- R: [15.932, 0.7035, 0.294],
22445
- G: [39.83, 0.1629, 0.7208],
22446
- B: [2.2404, 0.1472, 0.0309],
22447
- W: [66.28, 0.4681, 0.4182],
22448
- C: [73.58, 0.3166, 0.3397]
22788
+ var SegmentCounter = class {
22789
+ current = 0;
22790
+ next() {
22791
+ this.current = this.current + 1 & 255;
22792
+ if (this.current === 0)
22793
+ this.current = 1;
22794
+ return this.current;
22795
+ }
22449
22796
  };
22450
- var RGBCW_X = Object.fromEntries(Object.entries(RGBCW_CH).map(([k, [Y, x, y]]) => [k, [x * Y / y, Y, (1 - x - y) * Y / y]]));
22451
- var RGB_HEX = /^[0-9a-fA-F]{6}$/;
22797
+
22798
+ // dist/transport/rtc/live.js
22799
+ var LIVE_START = 1003;
22800
+ var LIVE_STOP = 1004;
22801
+ var LIVE_MEDIA = 1300;
22802
+ var LIVE_MEDIA_CHANNEL = 101;
22803
+ var LIVE_STREAM_ID = 1;
22804
+ var KEEPALIVE_MS = 29e3;
22805
+ var KEEPALIVE = Buffer.from("0009000010000000000000006300000000000000585a5948730400000000000000000002", "hex");
22806
+ var MEDIA_HEADER_LENGTH = 22;
22807
+ var STREAM_TYPE_HEVC = 1;
22808
+ function parseMediaBody(body) {
22809
+ if (body.length < MEDIA_HEADER_LENGTH || body[5] !== STREAM_TYPE_HEVC)
22810
+ return void 0;
22811
+ const length = body.readUInt32LE(0);
22812
+ if (body.length < MEDIA_HEADER_LENGTH + length)
22813
+ return void 0;
22814
+ return {
22815
+ data: body.subarray(MEDIA_HEADER_LENGTH, MEDIA_HEADER_LENGTH + length),
22816
+ width: body.readUInt16LE(10),
22817
+ height: body.readUInt16LE(12)
22818
+ };
22819
+ }
22820
+ var RtcLiveStream = class extends EventEmitter7 {
22821
+ opts;
22822
+ running = false;
22823
+ startSegment = -1;
22824
+ keepalive;
22825
+ width = 0;
22826
+ height = 0;
22827
+ onMedia = (frame) => this.onMediaFrame(frame);
22828
+ onCommand = (frame, linkType) => this.onCommandFrame(frame, linkType);
22829
+ onClose = () => this.fail(new Error(`rtc live ${this.tag}: session closed`));
22830
+ constructor(opts) {
22831
+ super();
22832
+ this.opts = opts;
22833
+ }
22834
+ get tag() {
22835
+ return `${this.opts.stationSn}#${this.opts.channel}`;
22836
+ }
22837
+ start() {
22838
+ if (this.running)
22839
+ return this;
22840
+ const { session, seg, accountId } = this.opts;
22841
+ this.running = true;
22842
+ session.on("mediaData", this.onMedia);
22843
+ session.on("commandData", this.onCommand);
22844
+ session.on("close", this.onClose);
22845
+ this.startSegment = seg.next();
22846
+ const sent = session.sendCommand(buildPortalPacket({
22847
+ commandId: PORTAL_CMD_SET_PAYLOAD,
22848
+ channel: PORTAL_STATION_CHANNEL,
22849
+ segment: this.startSegment,
22850
+ isResponse: LIVE_STREAM_ID,
22851
+ payload: {
22852
+ account_id: accountId,
22853
+ cmd: LIVE_START,
22854
+ payload: {
22855
+ ClientOS: "WEB",
22856
+ entrytype: 0,
22857
+ camera_type: 0,
22858
+ key: "",
22859
+ msg_id: 116,
22860
+ audio_chn: -1,
22861
+ streamtype: 2,
22862
+ stitch_mode: 1,
22863
+ chn_list: [{ index: 0, chn: this.opts.channel, sensor: 0, isUps: 0, isClicked: true }],
22864
+ pip_cord: { x1: 0, y1: 0, x2: 0, y2: 0 },
22865
+ station_video_type: 6,
22866
+ play_id: 1
22867
+ }
22868
+ }
22869
+ }));
22870
+ if (!sent) {
22871
+ queueMicrotask(() => this.fail(new Error(`rtc live ${this.tag}: command channel not open`)));
22872
+ return this;
22873
+ }
22874
+ this.keepalive = setInterval(() => {
22875
+ if (!session.sendRaw(KEEPALIVE))
22876
+ this.opts.logger?.warn?.(`[rtc] ${this.tag} keepalive not sent`);
22877
+ }, KEEPALIVE_MS);
22878
+ this.keepalive.unref?.();
22879
+ this.opts.logger?.debug?.(`[rtc] ${this.tag} live start sent`);
22880
+ return this;
22881
+ }
22882
+ stop() {
22883
+ if (!this.running)
22884
+ return;
22885
+ this.teardown();
22886
+ const { session, seg, accountId } = this.opts;
22887
+ session.sendCommand(buildPortalPacket({
22888
+ commandId: PORTAL_CMD_SET_PAYLOAD,
22889
+ channel: PORTAL_STATION_CHANNEL,
22890
+ segment: seg.next(),
22891
+ isResponse: LIVE_STREAM_ID,
22892
+ payload: { account_id: accountId, cmd: LIVE_STOP, payload: {} }
22893
+ }));
22894
+ this.emit("stop");
22895
+ }
22896
+ teardown() {
22897
+ this.running = false;
22898
+ if (this.keepalive)
22899
+ clearInterval(this.keepalive);
22900
+ this.keepalive = void 0;
22901
+ const { session } = this.opts;
22902
+ session.off("mediaData", this.onMedia);
22903
+ session.off("commandData", this.onCommand);
22904
+ session.off("close", this.onClose);
22905
+ }
22906
+ fail(err) {
22907
+ if (!this.running)
22908
+ return;
22909
+ this.teardown();
22910
+ this.emit("error", err);
22911
+ }
22912
+ /** The start's ACK: a non-zero result code ends the pull. */
22913
+ onCommandFrame(frame, linkType) {
22914
+ const p = parsePortalPacket(frame, linkType);
22915
+ if (!p?.isResponse || p.segment !== this.startSegment || p.commandId !== PORTAL_CMD_SET_PAYLOAD)
22916
+ return;
22917
+ if (p.errCode !== 0)
22918
+ this.fail(new Error(`rtc live ${this.tag}: start refused (err ${p.errCode})`));
22919
+ }
22920
+ onMediaFrame(frame) {
22921
+ const h = parsePortalHeader(frame);
22922
+ if (!h || h.commandId !== LIVE_MEDIA || h.channel !== LIVE_MEDIA_CHANNEL)
22923
+ return;
22924
+ if (h.paramLength > frame.length - PORTAL_HEADER_LENGTH)
22925
+ return;
22926
+ const media = parseMediaBody(frame.subarray(PORTAL_HEADER_LENGTH, PORTAL_HEADER_LENGTH + h.paramLength));
22927
+ if (!media)
22928
+ return;
22929
+ const { data, width, height } = media;
22930
+ if (width && height) {
22931
+ this.width = width;
22932
+ this.height = height;
22933
+ }
22934
+ const out = {
22935
+ codec: "h265",
22936
+ data,
22937
+ keyframe: hasIdr(data, "h265"),
22938
+ width: this.width,
22939
+ height: this.height
22940
+ };
22941
+ this.emit("video", out);
22942
+ }
22943
+ };
22944
+
22945
+ // dist/transport/rtc/session.js
22946
+ import { EventEmitter as EventEmitter10 } from "node:events";
22947
+
22948
+ // dist/transport/rtc/peer.js
22949
+ import { EventEmitter as EventEmitter8 } from "node:events";
22950
+
22951
+ // dist/transport/rtc/ptcs-framer.js
22952
+ var MAGIC3 = Buffer.from("PTCS", "ascii");
22953
+ var PTCS_HEADER_LENGTH = 28;
22954
+ var PTCS_DEFAULT_PAYLOAD_BYTES = 1e3;
22955
+ var FLAG_BASE = 16384;
22956
+ var FLAG_LAST = 1024;
22957
+ var LENGTH_MASK = 1023;
22958
+ var PtcsChannel = {
22959
+ COMMAND: 0,
22960
+ NOTIFY: 2,
22961
+ LIVE: 5
22962
+ };
22963
+ function linkTypeForChannel(channel) {
22964
+ if (channel === PtcsChannel.NOTIFY)
22965
+ return PortalLinkType.NOTIFY;
22966
+ if (channel === PtcsChannel.LIVE)
22967
+ return PortalLinkType.LIVE;
22968
+ return PortalLinkType.COMMAND;
22969
+ }
22970
+ var PTCS_STALE_MS = 15e3;
22971
+ function parsePtcsHeader(packet) {
22972
+ if (packet.length < PTCS_HEADER_LENGTH || packet.subarray(0, 4).compare(MAGIC3) !== 0)
22973
+ return void 0;
22974
+ const flags = packet.readUInt16LE(18);
22975
+ return {
22976
+ channel: packet[5],
22977
+ sequence: packet.readUInt16LE(6),
22978
+ frameId: packet.readUInt32LE(8),
22979
+ frameLength: packet.readUInt32LE(12),
22980
+ index: packet.readUInt16LE(16),
22981
+ last: (flags & FLAG_LAST) !== 0,
22982
+ payloadLength: flags & LENGTH_MASK
22983
+ };
22984
+ }
22985
+ function packetize(frame, opts) {
22986
+ const size = opts.payloadBytes ?? PTCS_DEFAULT_PAYLOAD_BYTES;
22987
+ if (size <= 0 || size > LENGTH_MASK)
22988
+ throw new RangeError(`PTCS payload size ${size} out of range`);
22989
+ const channel = opts.channel ?? PtcsChannel.COMMAND;
22990
+ const count2 = Math.max(1, Math.ceil(frame.length / size));
22991
+ const sequence = (opts.sequence ?? 0) & 65535;
22992
+ const packets = [];
22993
+ for (let i = 0; i < count2; i++) {
22994
+ const chunk = frame.subarray(i * size, Math.min(frame.length, (i + 1) * size));
22995
+ const last = i === count2 - 1;
22996
+ const packet = Buffer.alloc(PTCS_HEADER_LENGTH + size);
22997
+ MAGIC3.copy(packet, 0);
22998
+ packet[4] = 3;
22999
+ packet[5] = channel & 255;
23000
+ packet.writeUInt16LE(sequence, 6);
23001
+ packet.writeUInt32LE(opts.frameId >>> 0, 8);
23002
+ packet.writeUInt32LE(frame.length >>> 0, 12);
23003
+ packet.writeUInt16LE(i, 16);
23004
+ packet.writeUInt16LE(FLAG_BASE | (last ? FLAG_LAST : 0) | chunk.length, 18);
23005
+ chunk.copy(packet, PTCS_HEADER_LENGTH);
23006
+ packets.push(packet);
23007
+ }
23008
+ return packets;
23009
+ }
23010
+ var PtcsReassembler = class {
23011
+ onFrame;
23012
+ now;
23013
+ partials = /* @__PURE__ */ new Map();
23014
+ constructor(onFrame, now2 = Date.now) {
23015
+ this.onFrame = onFrame;
23016
+ this.now = now2;
23017
+ }
23018
+ push(packet) {
23019
+ const h = parsePtcsHeader(packet);
23020
+ if (!h)
23021
+ return false;
23022
+ const body = packet.subarray(PTCS_HEADER_LENGTH, PTCS_HEADER_LENGTH + h.payloadLength);
23023
+ if (body.length !== h.payloadLength)
23024
+ return false;
23025
+ const key = `${h.channel}:${h.frameId}`;
23026
+ const now2 = this.now();
23027
+ let p = this.partials.get(key);
23028
+ if (!p) {
23029
+ p = { channel: h.channel, frameLength: h.frameLength, chunks: /* @__PURE__ */ new Map(), touched: now2 };
23030
+ this.partials.set(key, p);
23031
+ }
23032
+ p.touched = now2;
23033
+ p.chunks.set(h.index, Buffer.from(body));
23034
+ if (h.last)
23035
+ p.lastIndex = h.index;
23036
+ if (p.lastIndex === void 0)
23037
+ return true;
23038
+ let total = 0;
23039
+ const parts = [];
23040
+ for (let i = 0; i <= p.lastIndex; i++) {
23041
+ const c = p.chunks.get(i);
23042
+ if (!c)
23043
+ return true;
23044
+ parts.push(c);
23045
+ total += c.length;
23046
+ }
23047
+ this.partials.delete(key);
23048
+ if (total !== p.frameLength)
23049
+ return false;
23050
+ this.onFrame(Buffer.concat(parts, total), p.channel);
23051
+ return true;
23052
+ }
23053
+ /** Drop frames that stopped arriving; call periodically. */
23054
+ expire() {
23055
+ const now2 = this.now();
23056
+ for (const [key, p] of this.partials) {
23057
+ if (now2 - p.touched > PTCS_STALE_MS)
23058
+ this.partials.delete(key);
23059
+ }
23060
+ }
23061
+ };
23062
+ function frameIdClock(now2 = Date.now) {
23063
+ let last = 0;
23064
+ return () => {
23065
+ let id = now2() >>> 0;
23066
+ if (id <= last)
23067
+ id = last + 1 >>> 0;
23068
+ last = id;
23069
+ return id;
23070
+ };
23071
+ }
23072
+ var PtcsFramer = class {
23073
+ onWire;
23074
+ onFrame;
23075
+ reassembler;
23076
+ sweep;
23077
+ ready = false;
23078
+ nextFrameId = frameIdClock();
23079
+ sequence = 0;
23080
+ /** Arm the two callbacks; `sendFrame` may be called from here on. */
23081
+ init(onWirePacket, onFrame) {
23082
+ this.onWire = onWirePacket;
23083
+ this.onFrame = onFrame;
23084
+ this.reassembler = new PtcsReassembler((frame, channel) => this.onFrame?.(frame, linkTypeForChannel(channel)));
23085
+ this.sweep = setInterval(() => this.reassembler?.expire(), 1e3);
23086
+ this.sweep.unref?.();
23087
+ this.ready = true;
23088
+ }
23089
+ isReady() {
23090
+ return this.ready;
23091
+ }
23092
+ sendFrame(portalPacket) {
23093
+ if (!this.ready)
23094
+ throw new Error("PTCS framer not initialised");
23095
+ const packets = packetize(portalPacket, { frameId: this.nextFrameId(), sequence: this.sequence });
23096
+ this.sequence = this.sequence + 1 & 65535;
23097
+ for (const packet of packets)
23098
+ this.onWire?.(packet);
23099
+ }
23100
+ recvPacket(wirePacket) {
23101
+ if (!this.ready)
23102
+ return;
23103
+ if (isPortalPacket(wirePacket)) {
23104
+ this.onFrame?.(wirePacket, PortalLinkType.COMMAND);
23105
+ return;
23106
+ }
23107
+ this.reassembler?.push(wirePacket);
23108
+ }
23109
+ destroy() {
23110
+ this.ready = false;
23111
+ if (this.sweep)
23112
+ clearInterval(this.sweep);
23113
+ this.sweep = void 0;
23114
+ this.reassembler = void 0;
23115
+ this.onWire = void 0;
23116
+ this.onFrame = void 0;
23117
+ }
23118
+ };
23119
+
23120
+ // dist/transport/rtc/scall-sdp.js
23121
+ var HUB_SDP_MID = "2";
23122
+ var ANKER_MAX_MESSAGE_SIZE = 262144;
23123
+ function scallJsonToSdp(json, now2 = Date.now) {
23124
+ let sdp = "";
23125
+ sdp += "v=0\r\n";
23126
+ sdp += `o=- ${Math.floor(now2())} 1 IN IP4 127.0.0.1\r
23127
+ `;
23128
+ sdp += "s=Anker Webrtc Stream\r\n";
23129
+ sdp += "t=0 0\r\n";
23130
+ sdp += `a=group:BUNDLE ${HUB_SDP_MID}\r
23131
+ `;
23132
+ sdp += "a=msid-semantic: WMS\r\n";
23133
+ sdp += "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n";
23134
+ sdp += "c=IN IP4 127.0.0.1\r\n";
23135
+ sdp += `a=mid:${HUB_SDP_MID}\r
23136
+ `;
23137
+ sdp += "a=ice-options:trickle\r\n";
23138
+ if (json.ice?.ufrag)
23139
+ sdp += `a=ice-ufrag:${json.ice.ufrag}\r
23140
+ `;
23141
+ if (json.ice?.pwd)
23142
+ sdp += `a=ice-pwd:${json.ice.pwd}\r
23143
+ `;
23144
+ if (json.ice?.fingerprint) {
23145
+ const fp = json.ice.fingerprint.replace(/(.{2})(?=.)/g, "$1:");
23146
+ sdp += `a=fingerprint:${json.ice.fingerprint_type ?? "sha-256"} ${fp}\r
23147
+ `;
23148
+ }
23149
+ sdp += `a=setup:${json.setup ?? "actpass"}\r
23150
+ `;
23151
+ sdp += "a=sctp-port:5000\r\n";
23152
+ sdp += `a=max-message-size:${ANKER_MAX_MESSAGE_SIZE}\r
23153
+ `;
23154
+ for (const c of json.candidate ?? [])
23155
+ sdp += `a=candidate:${c}\r
23156
+ `;
23157
+ return sdp;
23158
+ }
23159
+ function sdpToScallJson(sdp) {
23160
+ const json = { ice: { ufrag: "", pwd: "", fingerprint: "" } };
23161
+ const setup = sdp.match(/a=setup:([^\r\n]+)/)?.[1];
23162
+ if (setup && setup !== "actpass")
23163
+ json.setup = setup;
23164
+ const ufrag = sdp.match(/a=ice-ufrag:([^\r\n]+)/)?.[1];
23165
+ if (ufrag)
23166
+ json.ice.ufrag = ufrag;
23167
+ const pwd = sdp.match(/a=ice-pwd:([^\r\n]+)/)?.[1];
23168
+ if (pwd)
23169
+ json.ice.pwd = pwd;
23170
+ const fp = sdp.match(/a=fingerprint:([^\s]+)\s+([^\r\n]+)/);
23171
+ if (fp?.[2]) {
23172
+ json.ice.fingerprint_type = fp[1];
23173
+ json.ice.fingerprint = fp[2].replace(/:/g, "");
23174
+ }
23175
+ const candidates = [];
23176
+ for (const line of sdp.split(/\r\n|\r|\n/)) {
23177
+ const m = line.match(/^a=candidate:(.+)/);
23178
+ if (m?.[1])
23179
+ candidates.push(m[1]);
23180
+ }
23181
+ if (candidates.length)
23182
+ json.candidate = candidates;
23183
+ return json;
23184
+ }
23185
+ function iceCandidateType(candidate) {
23186
+ return candidate.match(/typ (\w+)/)?.[1] ?? "unknown";
23187
+ }
23188
+ function pinMaxMessageSize(sdp) {
23189
+ return sdp.replace(/a=max-message-size:\d+/g, `a=max-message-size:${ANKER_MAX_MESSAGE_SIZE}`);
23190
+ }
23191
+ function forceDtlsRole(sdp, role) {
23192
+ if (/a=setup:(active|passive|actpass)/.test(sdp))
23193
+ return sdp.replace(/a=setup:(active|passive|actpass)/g, `a=setup:${role}`);
23194
+ return sdp.replace(/(m=application[^\r\n]*\r?\n)/, `$1a=setup:${role}\r
23195
+ `);
23196
+ }
23197
+ function toWireCandidate(candidate) {
23198
+ return candidate.trim().replace(/^a=/, "");
23199
+ }
23200
+
23201
+ // dist/transport/rtc/peer.js
23202
+ var DATA_CHANNEL_LABELS = ["WebrtcDataChannel", "audio", "idr", "video", "notify", "download"];
23203
+ var COMMAND_CHANNEL = DATA_CHANNEL_LABELS[0];
23204
+ var DATA_CHANNEL_IDS = {
23205
+ WebrtcDataChannel: 0,
23206
+ audio: 2,
23207
+ idr: 4,
23208
+ video: 6,
23209
+ notify: 8,
23210
+ download: 10
23211
+ };
23212
+ function turnServers(turn) {
23213
+ const both = (hostname, port) => [
23214
+ { hostname, port, username: turn.turn_user, password: turn.turn_password, relayType: "TurnUdp" },
23215
+ { hostname, port, username: turn.turn_user, password: turn.turn_password, relayType: "TurnTcp" }
23216
+ ];
23217
+ const servers = both(turn.turn_addr, turn.turn_port);
23218
+ if (turn.alt_turn_addr && turn.alt_turn_port)
23219
+ servers.push(...both(turn.alt_turn_addr, turn.alt_turn_port));
23220
+ return servers;
23221
+ }
23222
+ var UNBUILT_ARCHES = /* @__PURE__ */ new Set(["arm", "ia32"]);
23223
+ async function loadNativePeerFactory() {
23224
+ let ndc;
23225
+ try {
23226
+ ndc = await import("node-datachannel");
23227
+ } catch (err) {
23228
+ const message = UNBUILT_ARCHES.has(process.arch) ? `the WebRTC transport for a HomeBase S1 Pro (T9000) needs 'node-datachannel', which has no build for ${process.arch}; a 64-bit OS is needed to drive a T9000` : "the WebRTC transport for a HomeBase S1 Pro (T9000) could not load 'node-datachannel'";
23229
+ throw new Error(message, { cause: err });
23230
+ }
23231
+ return (name, config) => new ndc.PeerConnection(name, config);
23232
+ }
23233
+ var ANSWER_TIMEOUT_MS = 15e3;
23234
+ var RtcPeer = class extends EventEmitter8 {
23235
+ opts;
23236
+ pc;
23237
+ channels = /* @__PURE__ */ new Map();
23238
+ framer;
23239
+ wireTally = /* @__PURE__ */ new Map();
23240
+ commandOpen = false;
23241
+ remoteSet = false;
23242
+ remoteMid = HUB_SDP_MID;
23243
+ handlingOffer = false;
23244
+ channelsCreated = false;
23245
+ gatheringDone = false;
23246
+ /** Set by the framer's wire callback when the native channel refused a packet mid-send. */
23247
+ wireSendFailed = false;
23248
+ pending = [];
23249
+ localAnswer;
23250
+ logger;
23251
+ constructor(opts = {}) {
23252
+ super();
23253
+ this.opts = opts;
23254
+ this.logger = opts.logger ?? noopLogger;
23255
+ }
23256
+ /** Create the native peer on the relay the hub granted in `scall 100`. */
23257
+ async init(turn) {
23258
+ if (this.pc)
23259
+ return;
23260
+ const createPeer = this.opts.createPeer ?? await loadNativePeerFactory();
23261
+ const config = {
23262
+ iceServers: turnServers(turn),
23263
+ iceTransportPolicy: this.opts.iceTransportPolicy ?? "relay",
23264
+ maxMessageSize: ANKER_MAX_MESSAGE_SIZE,
23265
+ enableIceTcp: true
23266
+ };
23267
+ const pc = createPeer("eufy-sdk", config);
23268
+ this.pc = pc;
23269
+ pc.onLocalDescription((sdp, type) => {
23270
+ if (String(type).toLowerCase() === "answer" && this.localAnswer) {
23271
+ clearTimeout(this.localAnswer.timer);
23272
+ this.localAnswer.resolve(sdp);
23273
+ this.localAnswer = void 0;
23274
+ }
23275
+ });
23276
+ pc.onLocalCandidate((candidate) => {
23277
+ if (!candidate)
23278
+ return;
23279
+ if (!this.acceptsCandidate(candidate))
23280
+ return;
23281
+ this.emit("iceCandidate", candidate);
23282
+ });
23283
+ pc.onGatheringStateChange((state) => {
23284
+ if (state === "complete" && !this.gatheringDone) {
23285
+ this.gatheringDone = true;
23286
+ this.emit("iceGatheringComplete");
23287
+ }
23288
+ });
23289
+ pc.onStateChange((state) => {
23290
+ this.logger.debug(`[rtc] peer state ${state}`);
23291
+ this.emit("connectionState", state);
23292
+ });
23293
+ pc.onDataChannel((dc) => this.wireChannel(dc.getLabel(), dc));
23294
+ }
23295
+ /**
23296
+ * The hub offered: apply the offer, declare the channels, return the answer SDP to signal back.
23297
+ *
23298
+ * The offer is pinned to `passive` before it is applied, so the native peer has one legal answer,
23299
+ * `active`: the role is fixed where it is decided, since rewriting the answer afterwards would change
23300
+ * only what is announced. The offer goes in before the channels are declared: `createDataChannel` on
23301
+ * a peer without a remote description starts its own negotiation and leaves it in `have-local-offer`.
23302
+ * The data channels need no m-line of their own; the offer's SCTP m-line carries them. Only an ANSWER
23303
+ * is taken as the local description: one read in `have-local-offer` is an offer.
23304
+ */
23305
+ async handleRemoteOffer(offerSdp) {
23306
+ const pc = this.pc;
23307
+ if (!pc)
23308
+ throw new Error("RTC peer not initialised");
23309
+ if (this.handlingOffer)
23310
+ throw new Error("RTC peer already handling an offer");
23311
+ this.handlingOffer = true;
23312
+ try {
23313
+ const offer = forceDtlsRole(offerSdp, "passive");
23314
+ const application = offer.split(/(?=^m=)/m).find((section) => section.startsWith("m=application "));
23315
+ this.remoteMid = application?.match(/^a=mid:([^\r\n]+)/m)?.[1] ?? HUB_SDP_MID;
23316
+ const answerWait = new Promise((resolve, reject) => {
23317
+ const timer = setTimeout(() => {
23318
+ this.localAnswer = void 0;
23319
+ reject(new Error("timed out waiting for the local SDP answer"));
23320
+ }, ANSWER_TIMEOUT_MS);
23321
+ this.localAnswer = { resolve, reject, timer };
23322
+ });
23323
+ pc.setRemoteDescription(offer, "offer");
23324
+ this.remoteSet = true;
23325
+ this.createChannels();
23326
+ const local = pc.localDescription();
23327
+ let answer = String(local?.type ?? "").toLowerCase() === "answer" ? local?.sdp ?? "" : "";
23328
+ if (!answer)
23329
+ answer = await answerWait;
23330
+ else if (this.localAnswer) {
23331
+ clearTimeout(this.localAnswer.timer);
23332
+ this.localAnswer = void 0;
23333
+ }
23334
+ this.flushPending();
23335
+ return pinMaxMessageSize(answer);
23336
+ } finally {
23337
+ this.handlingOffer = false;
23338
+ }
23339
+ }
23340
+ addRemoteCandidate(candidate) {
23341
+ if (!this.pc)
23342
+ return;
23343
+ if (!this.acceptsCandidate(candidate))
23344
+ return;
23345
+ if (!this.remoteSet || this.handlingOffer) {
23346
+ this.pending.push(candidate);
23347
+ return;
23348
+ }
23349
+ this.addNow(candidate);
23350
+ }
23351
+ /**
23352
+ * Send bytes on the command channel as they are, without PTCS framing; false when it isn't open. The
23353
+ * portal's data-channel keepalive rides the wire unframed.
23354
+ */
23355
+ sendRaw(bytes2) {
23356
+ const dc = this.channels.get(COMMAND_CHANNEL);
23357
+ if (!dc?.isOpen())
23358
+ return false;
23359
+ return dc.sendMessageBinary(bytes2);
23360
+ }
23361
+ /**
23362
+ * Send one portal packet on the command channel, through the framer. False when the channel is not
23363
+ * usable or the native send refused a wire packet, so a dropped frame does not read as success.
23364
+ */
23365
+ sendCommand(portalPacket) {
23366
+ const dc = this.channels.get(COMMAND_CHANNEL);
23367
+ if (!dc?.isOpen() || !this.commandOpen || !this.framer?.isReady())
23368
+ return false;
23369
+ this.wireSendFailed = false;
23370
+ try {
23371
+ this.framer.sendFrame(portalPacket);
23372
+ } catch (e) {
23373
+ this.logger.warn(`[rtc] command send failed: ${e instanceof Error ? e.message : String(e)}`);
23374
+ return false;
23375
+ }
23376
+ return !this.wireSendFailed;
23377
+ }
23378
+ /** Tear the peer down. A pending answer is rejected, so a `handleRemoteOffer` in flight settles. */
23379
+ close() {
23380
+ this.framer?.destroy();
23381
+ this.framer = void 0;
23382
+ if (this.localAnswer) {
23383
+ clearTimeout(this.localAnswer.timer);
23384
+ const pending = this.localAnswer;
23385
+ this.localAnswer = void 0;
23386
+ pending.reject(new Error("RTC peer closed while waiting for the local SDP answer"));
23387
+ }
23388
+ this.commandOpen = false;
23389
+ this.gatheringDone = false;
23390
+ this.pc?.close();
23391
+ this.pc = void 0;
23392
+ this.channels.clear();
23393
+ this.channelsCreated = false;
23394
+ this.remoteSet = false;
23395
+ this.pending.length = 0;
23396
+ }
23397
+ acceptsCandidate(candidate) {
23398
+ return this.opts.iceTransportPolicy === "all" || iceCandidateType(candidate) === "relay";
23399
+ }
23400
+ createChannels() {
23401
+ if (!this.pc || this.channelsCreated)
23402
+ return;
23403
+ this.channelsCreated = true;
23404
+ for (const label of DATA_CHANNEL_LABELS) {
23405
+ const dc = this.pc.createDataChannel(label, { id: DATA_CHANNEL_IDS[label], unordered: false });
23406
+ this.wireChannel(label, dc);
23407
+ }
23408
+ }
23409
+ /**
23410
+ * Wire one data channel. Every channel feeds the framer once the command channel has opened it; a
23411
+ * message before that has nothing to reassemble into and is dropped.
23412
+ */
23413
+ wireChannel(label, dc) {
23414
+ if (this.channels.has(label))
23415
+ return;
23416
+ this.channels.set(label, dc);
23417
+ dc.onOpen(() => {
23418
+ this.logger.debug(`[rtc] data channel open ${label}`);
23419
+ if (label !== COMMAND_CHANNEL)
23420
+ return;
23421
+ if (!this.framer) {
23422
+ const framer = new PtcsFramer();
23423
+ framer.init((packet) => {
23424
+ if (!dc.isOpen() || !dc.sendMessageBinary(packet))
23425
+ this.wireSendFailed = true;
23426
+ }, (frame, linkType) => this.emit("data", frame, linkType));
23427
+ this.framer = framer;
23428
+ }
23429
+ this.commandOpen = true;
23430
+ this.emit("commandChannelOpen");
23431
+ });
23432
+ dc.onClosed(() => {
23433
+ this.logger.debug(`[rtc] data channel closed ${label}`);
23434
+ if (label !== COMMAND_CHANNEL)
23435
+ return;
23436
+ const wasOpen = this.commandOpen;
23437
+ this.commandOpen = false;
23438
+ if (wasOpen)
23439
+ this.emit("commandChannelClosed");
23440
+ });
23441
+ dc.onError((err) => this.emit("error", new Error(`RTC data channel ${label}: ${err}`)));
23442
+ dc.onMessage((msg) => {
23443
+ const buf = typeof msg === "string" ? Buffer.from(msg) : Buffer.isBuffer(msg) ? msg : Buffer.from(msg);
23444
+ const n = (this.wireTally.get(label) ?? 0) + 1;
23445
+ this.wireTally.set(label, n);
23446
+ if (n <= 3 || n % 100 === 0) {
23447
+ this.logger.debug(`[rtc] wire ${label} #${n} ${buf.length}B ${buf.subarray(0, 8).toString("hex")}`);
23448
+ }
23449
+ this.framer?.recvPacket(buf);
23450
+ });
23451
+ }
23452
+ addNow(candidate) {
23453
+ try {
23454
+ this.pc?.addRemoteCandidate(candidate, this.remoteMid);
23455
+ } catch (e) {
23456
+ this.logger.warn(`[rtc] addRemoteCandidate failed: ${e instanceof Error ? e.message : String(e)}`);
23457
+ }
23458
+ }
23459
+ flushPending() {
23460
+ const queued = this.pending.splice(0);
23461
+ for (const c of queued)
23462
+ this.addNow(c);
23463
+ }
23464
+ };
23465
+
23466
+ // dist/transport/rtc/signaling.js
23467
+ import { EventEmitter as EventEmitter9 } from "node:events";
23468
+ import { createHmac as createHmac3, randomUUID as randomUUID2 } from "node:crypto";
23469
+ var RTC_WS_PATH = "/v1/rtc/ws/join?reqtype=nvr";
23470
+ var RTC_SIGN_PATH = "/v1/smart/nvr/ws/sign";
23471
+ var PORTAL_ORIGIN = "https://security.eufy.com";
23472
+ var SIGNALING_KEEPALIVE_MS = 25e3;
23473
+ var SIGNALING_CONNECT_TIMEOUT_MS = 15e3;
23474
+ var SOURCE = "WEB";
23475
+ function sessionAccount(channelId, adminUserId, ts, authToken) {
23476
+ return createHmac3("sha256", authToken).update(`${channelId}${adminUserId}${ts}`).digest("hex");
23477
+ }
23478
+ var WS_OPEN = 1;
23479
+ var defaultSocket = (url, init) => new WebSocket(url, {
23480
+ protocols: init.protocols,
23481
+ headers: { Origin: init.origin }
23482
+ });
23483
+ var RtcSignalingClient = class extends EventEmitter9 {
23484
+ opts;
23485
+ ws;
23486
+ sign;
23487
+ keepalive;
23488
+ wsUrl;
23489
+ signUrl;
23490
+ wsRegion;
23491
+ fetchImpl;
23492
+ createSocket;
23493
+ logger;
23494
+ now;
23495
+ makeMsgId;
23496
+ constructor(opts) {
23497
+ super();
23498
+ this.opts = opts;
23499
+ const prefix = (opts.shard.split("-")[0] || "us").toLowerCase();
23500
+ const smartHost = prefix === "us" ? "security-smart.eufylife.com" : `security-smart-${prefix}.eufylife.com`;
23501
+ this.wsUrl = `wss://${smartHost}${RTC_WS_PATH}`;
23502
+ this.signUrl = `https://${smartHost}${RTC_SIGN_PATH}`;
23503
+ this.wsRegion = prefix.toUpperCase();
23504
+ this.fetchImpl = opts.fetch ?? fetch;
23505
+ this.createSocket = opts.createSocket ?? defaultSocket;
23506
+ this.logger = opts.logger ?? noopLogger;
23507
+ this.now = opts.now ?? Date.now;
23508
+ this.makeMsgId = opts.makeMsgId ?? (() => randomUUID2().replace(/-/g, ""));
23509
+ }
23510
+ get isOpen() {
23511
+ return this.ws?.readyState === WS_OPEN;
23512
+ }
23513
+ /** Step 1: the sign blob the socket and every auth message carry. A non-JSON body is reported by status. */
23514
+ async fetchSign() {
23515
+ const res = await this.fetchImpl(this.signUrl, {
23516
+ headers: {
23517
+ "Web-Country": this.opts.country.toUpperCase(),
23518
+ "X-Auth-Token": this.opts.authToken,
23519
+ "App-Name": "eufy_mega",
23520
+ "Model-Type": "WEB",
23521
+ GToken: this.opts.gtoken,
23522
+ Origin: PORTAL_ORIGIN
23523
+ }
23524
+ });
23525
+ const body = await res.json().catch(() => ({})) ?? {};
23526
+ if (!res.ok || body.code !== 0 || !body.data) {
23527
+ throw new Error(`RTC sign for ${this.opts.stationSn} refused: HTTP ${res.status} code ${body.code ?? "?"} ${withoutTokenEcho(body.msg ?? "")}`.trim());
23528
+ }
23529
+ this.sign = body.data;
23530
+ return body.data;
23531
+ }
23532
+ /**
23533
+ * Step 2: open the socket and send the first auth; resolves on `open`. A socket that closes or errors
23534
+ * before it ever opened rejects, so the call always settles.
23535
+ */
23536
+ async connect() {
23537
+ if (this.ws)
23538
+ return;
23539
+ const sign = this.sign ?? await this.fetchSign();
23540
+ const auth = {
23541
+ region: this.wsRegion,
23542
+ type: "NVR",
23543
+ sn: this.opts.stationSn,
23544
+ token: this.opts.authToken,
23545
+ gtoken: this.opts.gtoken,
23546
+ sign,
23547
+ appName: "eufy_mega",
23548
+ modelType: "WEB"
23549
+ };
23550
+ const protocols = ["v1", Buffer.from(JSON.stringify(auth)).toString("base64url")];
23551
+ this.logger.debug(`[rtc] ${this.opts.stationSn} signalling connect ${this.wsUrl}`);
23552
+ await new Promise((resolve, reject) => {
23553
+ const timer = setTimeout(() => {
23554
+ reject(new Error(`RTC signalling connect timeout after ${SIGNALING_CONNECT_TIMEOUT_MS}ms`));
23555
+ this.close();
23556
+ }, SIGNALING_CONNECT_TIMEOUT_MS);
23557
+ const ws = this.createSocket(this.wsUrl, { protocols, origin: PORTAL_ORIGIN });
23558
+ this.ws = ws;
23559
+ let opened = false;
23560
+ ws.addEventListener("open", () => {
23561
+ opened = true;
23562
+ clearTimeout(timer);
23563
+ this.sendAuth(sign);
23564
+ this.startKeepalive();
23565
+ this.emit("open");
23566
+ resolve();
23567
+ });
23568
+ ws.addEventListener("message", (ev) => {
23569
+ void this.handleWireMessage(ev.data);
23570
+ });
23571
+ ws.addEventListener("close", (ev) => {
23572
+ clearTimeout(timer);
23573
+ this.stopKeepalive();
23574
+ this.ws = void 0;
23575
+ const code = ev.code ?? 1006;
23576
+ const reason = ev.reason ?? "";
23577
+ this.logger.debug(`[rtc] ${this.opts.stationSn} signalling closed ${code} ${reason}`);
23578
+ if (!opened)
23579
+ reject(new Error(`RTC signalling closed before open: ${code} ${reason}`.trim()));
23580
+ this.emit("close", code, reason);
23581
+ });
23582
+ ws.addEventListener("error", (ev) => {
23583
+ clearTimeout(timer);
23584
+ const detail = ev ?? {};
23585
+ const cause = detail.error?.message ?? detail.error?.code ?? detail.message ?? "";
23586
+ reject(new Error(`RTC signalling socket error${cause ? ": " + cause : ""}`));
23587
+ });
23588
+ });
23589
+ }
23590
+ /** `action 1`, also what keeps the socket alive when re-sent. */
23591
+ sendAuth(sign) {
23592
+ const s = sign ?? this.sign;
23593
+ if (!s)
23594
+ throw new Error("RTC signalling: no sign to authenticate with");
23595
+ this.sendEnvelope("0", {
23596
+ code: 200,
23597
+ action: 1,
23598
+ data: s,
23599
+ sn: this.opts.stationSn,
23600
+ source: SOURCE,
23601
+ ts: Math.floor(this.now() / 1e3)
23602
+ });
23603
+ }
23604
+ /**
23605
+ * `action 3`, a session message on channel 0, the hub's own session; `scall` opens the negotiation.
23606
+ * `subSn` is empty for the hub's session.
23607
+ */
23608
+ sendSession(dataType, payload = {}) {
23609
+ const channelId = 0;
23610
+ const ts = Math.floor(this.now() / 1e3);
23611
+ const inner = {
23612
+ code: 200,
23613
+ action: 3,
23614
+ sessionId: this.sign,
23615
+ sn: this.opts.stationSn,
23616
+ subSn: "",
23617
+ channelId,
23618
+ isResponse: 0,
23619
+ dataType,
23620
+ source: SOURCE,
23621
+ ts,
23622
+ data: JSON.stringify({
23623
+ timestamp: ts,
23624
+ account: sessionAccount(channelId, this.opts.adminUserId, ts, this.opts.authToken),
23625
+ ...payload
23626
+ })
23627
+ };
23628
+ this.sendEnvelope(`${this.opts.authToken}_${this.makeMsgId()}`, inner);
23629
+ }
23630
+ sendCall() {
23631
+ this.sendSession(this.opts.signalingMode ?? "scall");
23632
+ }
23633
+ sendAck() {
23634
+ this.sendSession("ack");
23635
+ }
23636
+ /** The SDP answer, encoded for the negotiated call format, in an `info`. */
23637
+ sendInfoSdp(sdp) {
23638
+ this.sendSession("info", { sdp });
23639
+ }
23640
+ /** Trickle a candidate on the session's channel, like its SDP answer. An empty candidate ends them. */
23641
+ sendInfoCandidate(candidate) {
23642
+ this.sendSession("info", { candidate });
23643
+ }
23644
+ sendHangup() {
23645
+ this.sendSession("hangup");
23646
+ }
23647
+ close() {
23648
+ this.stopKeepalive();
23649
+ const ws = this.ws;
23650
+ this.ws = void 0;
23651
+ try {
23652
+ ws?.close();
23653
+ } catch {
23654
+ }
23655
+ }
23656
+ startKeepalive() {
23657
+ this.stopKeepalive();
23658
+ this.keepalive = setInterval(() => {
23659
+ if (!this.isOpen)
23660
+ return;
23661
+ try {
23662
+ this.sendAuth();
23663
+ } catch (e) {
23664
+ this.logger.warn(`[rtc] ${this.opts.stationSn} signalling keepalive failed`, e);
23665
+ }
23666
+ }, SIGNALING_KEEPALIVE_MS);
23667
+ this.keepalive.unref?.();
23668
+ }
23669
+ stopKeepalive() {
23670
+ if (this.keepalive)
23671
+ clearInterval(this.keepalive);
23672
+ this.keepalive = void 0;
23673
+ }
23674
+ sendEnvelope(msgid, inner) {
23675
+ if (!this.isOpen || !this.ws)
23676
+ throw new Error("RTC signalling not connected");
23677
+ const envelope = { msgid, data: JSON.stringify(inner) };
23678
+ this.ws.send(JSON.stringify(envelope));
23679
+ }
23680
+ async handleWireMessage(raw) {
23681
+ let text2;
23682
+ if (typeof raw === "string")
23683
+ text2 = raw;
23684
+ else if (Buffer.isBuffer(raw))
23685
+ text2 = raw.toString("utf8");
23686
+ else if (raw instanceof ArrayBuffer)
23687
+ text2 = Buffer.from(raw).toString("utf8");
23688
+ else if (typeof raw?.text === "function")
23689
+ text2 = await raw.text();
23690
+ else
23691
+ return;
23692
+ let envelope;
23693
+ let inner;
23694
+ try {
23695
+ envelope = JSON.parse(text2);
23696
+ if (typeof envelope?.data !== "string")
23697
+ return;
23698
+ inner = JSON.parse(envelope.data);
23699
+ } catch {
23700
+ return;
23701
+ }
23702
+ this.emit("message", inner, envelope);
23703
+ }
23704
+ };
23705
+
23706
+ // dist/transport/rtc/session.js
23707
+ var AUTH_TIMEOUT_MS = 15e3;
23708
+ var RtcSession = class extends EventEmitter10 {
23709
+ opts;
23710
+ signaling;
23711
+ peer;
23712
+ logger;
23713
+ turn;
23714
+ authOk = false;
23715
+ authWaiter;
23716
+ connected = false;
23717
+ closed = false;
23718
+ closeAnnounced = false;
23719
+ sdpHandled = false;
23720
+ chain = Promise.resolve();
23721
+ constructor(opts) {
23722
+ super();
23723
+ this.opts = opts;
23724
+ this.logger = opts.logger ?? noopLogger;
23725
+ this.signaling = (opts.createSignaling ?? ((o) => new RtcSignalingClient(o)))(opts);
23726
+ this.peer = (opts.createPeer ?? ((o) => new RtcPeer(o)))({ logger: this.logger, ...opts.peer });
23727
+ this.signaling.on("message", (inner) => {
23728
+ this.chain = this.chain.then(() => this.onSignaling(inner)).catch((e) => {
23729
+ this.emit("error", e instanceof Error ? e : new Error(String(e)));
23730
+ });
23731
+ });
23732
+ this.signaling.on("close", () => {
23733
+ this.connected = false;
23734
+ this.announceClose();
23735
+ });
23736
+ this.signaling.on("error", (e) => this.emit("error", e));
23737
+ this.peer.on("iceCandidate", (c) => this.trickle(toWireCandidate(c)));
23738
+ this.peer.on("iceGatheringComplete", () => this.trickle(""));
23739
+ this.peer.on("commandChannelOpen", () => {
23740
+ if (this.connected)
23741
+ return;
23742
+ this.connected = true;
23743
+ this.logger.debug(`[rtc] ${this.opts.stationSn} command channel open`);
23744
+ this.emit("connected");
23745
+ });
23746
+ this.peer.on("commandChannelClosed", () => {
23747
+ if (!this.connected)
23748
+ return;
23749
+ this.connected = false;
23750
+ this.logger.debug(`[rtc] ${this.opts.stationSn} command channel closed`);
23751
+ this.announceClose();
23752
+ });
23753
+ this.peer.on("connectionState", (state) => {
23754
+ if ((state === "failed" || state === "closed") && this.connected) {
23755
+ this.connected = false;
23756
+ this.announceClose();
23757
+ }
23758
+ });
23759
+ this.peer.on("error", (e) => this.emit("error", e));
23760
+ this.peer.on("data", (frame, linkType) => {
23761
+ if (linkType === PortalLinkType.LIVE)
23762
+ this.emit("mediaData", frame);
23763
+ else
23764
+ this.emit("commandData", frame, linkType);
23765
+ });
23766
+ }
23767
+ get isConnected() {
23768
+ return this.connected;
23769
+ }
23770
+ /**
23771
+ * Start the sequence; resolves once the call is sent. `connected` fires when the channel opens. A session
23772
+ * closed by the time the sign fetch or the auth completes rejects instead of opening the socket or
23773
+ * placing the call.
23774
+ */
23775
+ async connect() {
23776
+ await this.signaling.fetchSign();
23777
+ if (this.closed)
23778
+ throw new Error("RTC session closed before the call was placed");
23779
+ await this.signaling.connect();
23780
+ await this.waitForAuth();
23781
+ if (this.closed)
23782
+ throw new Error("RTC session closed before the call was placed");
23783
+ this.logger.debug(`[rtc] ${this.opts.stationSn} authenticated \u2014 ${this.opts.signalingMode ?? "scall"}`);
23784
+ this.signaling.sendCall();
23785
+ }
23786
+ /** Send one portal packet; false when the command channel isn't open. */
23787
+ sendCommand(portalPacket) {
23788
+ return this.peer.sendCommand(portalPacket);
23789
+ }
23790
+ /** Send unframed bytes on the command channel; false when it isn't open. */
23791
+ sendRaw(bytes2) {
23792
+ return this.peer.sendRaw(bytes2);
23793
+ }
23794
+ /**
23795
+ * Hang up and tear both sides down; `close` fires once, here if nothing announced it before. A
23796
+ * `connect()` still waiting for the signalling auth is rejected and its timer stopped.
23797
+ */
23798
+ close() {
23799
+ if (this.closed)
23800
+ return;
23801
+ this.closed = true;
23802
+ this.connected = false;
23803
+ try {
23804
+ if (this.signaling.isOpen)
23805
+ this.signaling.sendHangup();
23806
+ } catch {
23807
+ }
23808
+ this.signaling.close();
23809
+ this.peer.close();
23810
+ this.settleAuth(new Error("RTC session closed while waiting for signalling auth"));
23811
+ this.announceClose();
23812
+ }
23813
+ /**
23814
+ * Trickle one local candidate, or the empty end-of-candidates. The native peer can report one after the
23815
+ * signalling socket has closed, and sending then throws inside a native callback, where the throw can't
23816
+ * be caught and aborts the process. A candidate with no open socket is dropped.
23817
+ */
23818
+ trickle(candidate) {
23819
+ if (!this.signaling.isOpen)
23820
+ return;
23821
+ this.signaling.sendInfoCandidate(candidate);
23822
+ }
23823
+ announceClose() {
23824
+ if (this.closeAnnounced)
23825
+ return;
23826
+ this.closeAnnounced = true;
23827
+ this.emit("close");
23828
+ }
23829
+ waitForAuth() {
23830
+ if (this.authOk)
23831
+ return Promise.resolve();
23832
+ return new Promise((resolve, reject) => {
23833
+ const timer = setTimeout(() => {
23834
+ this.authWaiter = void 0;
23835
+ reject(new Error("RTC signalling auth timeout"));
23836
+ }, AUTH_TIMEOUT_MS);
23837
+ this.authWaiter = { resolve, reject, timer };
23838
+ });
23839
+ }
23840
+ /** Settle a pending auth wait: resolve it, or reject it with `err`; either way its timer stops. */
23841
+ settleAuth(err) {
23842
+ const waiter = this.authWaiter;
23843
+ if (!waiter)
23844
+ return;
23845
+ this.authWaiter = void 0;
23846
+ clearTimeout(waiter.timer);
23847
+ if (err)
23848
+ waiter.reject(err);
23849
+ else
23850
+ waiter.resolve();
23851
+ }
23852
+ async onSignaling(inner) {
23853
+ if (inner.action === 1 && inner.code === 200) {
23854
+ this.authOk = true;
23855
+ this.settleAuth();
23856
+ }
23857
+ if (!inner.data)
23858
+ return;
23859
+ let payload;
23860
+ try {
23861
+ payload = JSON.parse(inner.data);
23862
+ } catch {
23863
+ return;
23864
+ }
23865
+ switch (inner.dataType) {
23866
+ case "scall":
23867
+ case "call":
23868
+ await this.onCall(payload);
23869
+ return;
23870
+ case "info":
23871
+ await this.onInfo(payload);
23872
+ return;
23873
+ case "hangup":
23874
+ this.logger.debug(`[rtc] ${this.opts.stationSn} hub hung up`);
23875
+ return;
23876
+ default:
23877
+ return;
23878
+ }
23879
+ }
23880
+ /** A `scall` status: `100` grants the relay, `200` is acknowledged, `486`/`408` fail the session. */
23881
+ async onCall(payload) {
23882
+ if (this.closed)
23883
+ return;
23884
+ const status = payload.status;
23885
+ if (status === 100 && payload.turn) {
23886
+ this.turn = payload.turn;
23887
+ await this.peer.init(payload.turn);
23888
+ return;
23889
+ }
23890
+ if (status === 200) {
23891
+ this.signaling.sendAck();
23892
+ return;
23893
+ }
23894
+ if (status === 486 || status === 408) {
23895
+ this.emit("error", new Error(`RTC ${this.opts.stationSn} scall answered ${status}`));
23896
+ this.close();
23897
+ }
23898
+ }
23899
+ /**
23900
+ * An `info`: trickle ICE, in either of the two shapes the hub sends, or the hub's SDP offer. The offer
23901
+ * is answered only once a TURN grant is in: the peer is relay-only, so an offer ahead of `scall 100`
23902
+ * is reported and left unanswered.
23903
+ */
23904
+ async onInfo(payload) {
23905
+ if (this.closed)
23906
+ return;
23907
+ if (payload.format === "CANDIDATE") {
23908
+ if (payload.value)
23909
+ this.peer.addRemoteCandidate(payload.value);
23910
+ return;
23911
+ }
23912
+ if (payload.candidate !== void 0) {
23913
+ if (payload.candidate)
23914
+ this.peer.addRemoteCandidate(payload.candidate);
23915
+ return;
23916
+ }
23917
+ const sdpText = payload.value ?? payload.sdp;
23918
+ if (!sdpText || payload.format !== "SDP" && !payload.sdp)
23919
+ return;
23920
+ if (this.sdpHandled)
23921
+ return;
23922
+ if (!this.turn) {
23923
+ this.emit("error", new Error(`RTC ${this.opts.stationSn} offered before granting a relay`));
23924
+ return;
23925
+ }
23926
+ this.sdpHandled = true;
23927
+ let offer;
23928
+ try {
23929
+ offer = scallJsonToSdp(JSON.parse(sdpText));
23930
+ } catch {
23931
+ offer = sdpText;
23932
+ }
23933
+ const answer = await this.peer.handleRemoteOffer(offer);
23934
+ this.signaling.sendInfoSdp(this.opts.signalingMode === "call" ? answer : JSON.stringify(sdpToScallJson(answer)));
23935
+ this.logger.debug(`[rtc] ${this.opts.stationSn} answered the hub's offer`);
23936
+ }
23937
+ };
23938
+
23939
+ // dist/transport/rtc/command-router.js
23940
+ var PORTAL_CMD_CONTROL_PAYLOAD = 1700;
23941
+ var PORTAL_CMD_NOTIFY_PAYLOAD = 1351;
23942
+ var ACK_TIMEOUT_MS = 8e3;
23943
+ var CONNECT_TIMEOUT_MS2 = 12e3;
23944
+ var IDLE_CLOSE_MS = 6e4;
23945
+ var StationStreamBusyError = class extends Error {
23946
+ constructor(stationSn, servingSn) {
23947
+ super(`rtc live: ${stationSn} is serving ${servingSn}; the station streams one camera at a time`);
23948
+ this.name = "StationStreamBusyError";
23949
+ }
23950
+ };
23951
+ var RtcCommandRouter = class {
23952
+ deps;
23953
+ sessions = /* @__PURE__ */ new Map();
23954
+ lives = /* @__PURE__ */ new Map();
23955
+ constructor(deps) {
23956
+ this.deps = deps;
23957
+ }
23958
+ async dispatchCommand(route, cmd) {
23959
+ if (cmd.kind !== "set-payload" && cmd.kind !== "set-json") {
23960
+ throw new Error(`rtc: ${cmd.kind} is not routable over the RTC control channel (only set-payload or set-json)`);
23961
+ }
23962
+ const identity = this.deps.identity();
23963
+ if (!identity)
23964
+ throw new Error(`rtc: not logged in, cannot drive ${route.stationSn}`);
23965
+ const { stationSn } = route;
23966
+ const adminUserId = route.adminUserId || identity.userId;
23967
+ const channel = route.attached ? cmd.channel : PORTAL_STATION_CHANNEL;
23968
+ const st = await this.stationSession(route, adminUserId, identity);
23969
+ const outerCmd = cmd.kind === "set-json" ? PORTAL_CMD_CONTROL_PAYLOAD : PORTAL_CMD_SET_PAYLOAD;
23970
+ const innerCmd = cmd.kind === "set-json" ? cmd.param : cmd.cmd;
23971
+ const payload = cmd.kind === "set-json" ? { account_id: adminUserId, cmd: cmd.param, commandType: cmd.param, data: cmd.data } : { account_id: adminUserId, cmd: cmd.cmd, mValue3: cmd.mValue3 ?? 0, payload: cmd.payload };
23972
+ const segment = st.seg.next();
23973
+ const packet = buildPortalPacket({ commandId: outerCmd, channel, segment, payload });
23974
+ const run = st.queue.then(() => this.sendAwaitAck(stationSn, st, packet, outerCmd, innerCmd, channel, segment));
23975
+ st.queue = run.catch(() => void 0);
23976
+ return run;
23977
+ }
23978
+ /**
23979
+ * The media of a camera on a T9000: live video, a readable feed and a live still over the station's
23980
+ * session. Recording has no wire here and is refused; the optional members it has no wire for are absent.
23981
+ */
23982
+ mediaProviderFor(route) {
23983
+ return {
23984
+ live: (opts) => this.withLiveSource(route, opts ?? {}, (source) => attachUnlessAborted(source, opts?.signal)),
23985
+ openReadable: (opts) => this.withLiveSource(route, opts ?? {}, (source) => openReadableFromConsumer(attachUnlessAborted(source, opts?.signal), opts)),
23986
+ snapshotLive: (opts) => this.withLiveSource(route, opts ?? {}, (source) => captureSnapshotFromShared(source, { ...opts, logger: this.deps.logger, ffmpegPath: this.deps.ffmpegPath })).catch((e) => {
23987
+ if (!(e instanceof StationStreamBusyError))
23988
+ throw e;
23989
+ throw new LiveSnapshotUnavailableError("source-failed", e.message, { cause: e });
23990
+ }),
23991
+ record: async () => {
23992
+ throw new Error(`record is not available for ${route.cameraSn} over the T9000 control channel`);
23993
+ }
23994
+ };
23995
+ }
23996
+ /**
23997
+ * Tear down every station session (logout / shutdown). Each live source is disposed before its session
23998
+ * closes, so its consumers end cleanly and its stop still rides the session.
23999
+ */
24000
+ close() {
24001
+ for (const [sn, live] of this.lives) {
24002
+ this.lives.delete(sn);
24003
+ live.source.dispose();
24004
+ }
24005
+ for (const [sn, st] of this.sessions)
24006
+ this.drop(sn, st);
24007
+ }
24008
+ /**
24009
+ * Hand `use` the station's live source for this camera, in the same turn the source is created or reused,
24010
+ * so a consumer it attaches is counted before any other caller looks.
24011
+ *
24012
+ * The station streams one camera at a time. Another camera whose source has consumers refuses this one,
24013
+ * before the session is awaited and again after; one with none (never attached or lingering)
24014
+ * holds nothing a viewer needs, so it is disposed and the slot taken. The first caller's
24015
+ * {@link SharedSourceHints} configure a new source.
24016
+ */
24017
+ async withLiveSource(route, opts, use) {
24018
+ opts.signal?.throwIfAborted();
24019
+ this.refuseIfWatched(route);
24020
+ const identity = this.deps.identity();
24021
+ if (!identity)
24022
+ throw new Error(`rtc: not logged in, cannot open ${route.stationSn}`);
24023
+ const accountId = route.adminUserId || identity.userId;
24024
+ const st = await abortable(this.stationSession(route, accountId, identity), opts.signal);
24025
+ this.refuseIfWatched(route);
24026
+ const current = this.lives.get(route.stationSn);
24027
+ if (current && current.cameraSn !== route.cameraSn) {
24028
+ this.deps.logger?.debug?.(`[rtc] ${route.stationSn} releasing the unwatched source of ${current.cameraSn} for ${route.cameraSn}`);
24029
+ this.lives.delete(route.stationSn);
24030
+ current.source.dispose();
24031
+ }
24032
+ let live = this.lives.get(route.stationSn);
24033
+ if (!live) {
24034
+ live = { cameraSn: route.cameraSn, source: this.newLiveSource(route, st, accountId, opts) };
24035
+ this.lives.set(route.stationSn, live);
24036
+ }
24037
+ return await use(live.source);
24038
+ }
24039
+ /** Refuse a camera while another camera on its station has consumers. */
24040
+ refuseIfWatched(route) {
24041
+ const current = this.lives.get(route.stationSn);
24042
+ if (current && current.cameraSn !== route.cameraSn && current.source.consumerCount > 0) {
24043
+ throw new StationStreamBusyError(route.stationSn, current.cameraSn);
24044
+ }
24045
+ }
24046
+ newLiveSource(route, st, accountId, hints) {
24047
+ let leased = false;
24048
+ const release = () => {
24049
+ if (!leased)
24050
+ return;
24051
+ leased = false;
24052
+ st.leases = Math.max(0, st.leases - 1);
24053
+ this.touch(route.stationSn, st);
24054
+ };
24055
+ const source = new SharedLiveSource({
24056
+ makeStream: () => new RtcLiveStream({
24057
+ session: st.session,
24058
+ seg: st.seg,
24059
+ stationSn: route.stationSn,
24060
+ channel: route.channel,
24061
+ accountId,
24062
+ logger: this.deps.logger
24063
+ }),
24064
+ label: `${route.stationSn}#${route.channel}`,
24065
+ logger: this.deps.logger,
24066
+ powered: hints.powered,
24067
+ preBufferSeconds: hints.preBufferSeconds,
24068
+ onActive: () => {
24069
+ if (leased)
24070
+ return;
24071
+ leased = true;
24072
+ st.leases++;
24073
+ if (st.idle)
24074
+ clearTimeout(st.idle);
24075
+ },
24076
+ onStopped: () => {
24077
+ release();
24078
+ if (this.lives.get(route.stationSn)?.source === source)
24079
+ this.lives.delete(route.stationSn);
24080
+ }
24081
+ });
24082
+ return source;
24083
+ }
24084
+ /**
24085
+ * Completes on the command ACK or a correlated control-result notification. The notification must
24086
+ * match the request channel, parameter and segment and contain a structured payload. Receipt does
24087
+ * not establish physical actuation. The command is sent once, bounded by {@link ACK_TIMEOUT_MS}.
24088
+ */
24089
+ sendAwaitAck(sn, st, packet, outerCmd, innerCmd, channel, segment) {
24090
+ return new Promise((resolve, reject) => {
24091
+ const onData = (frame, linkType) => {
24092
+ const p = parsePortalPacket(frame, linkType);
24093
+ if (!p || p.segment !== segment)
24094
+ return;
24095
+ const acknowledgement = linkType === PortalLinkType.COMMAND && p.commandId === outerCmd && !!p.isResponse;
24096
+ const d = p.data;
24097
+ const notification = outerCmd === PORTAL_CMD_CONTROL_PAYLOAD && linkType === PortalLinkType.NOTIFY && p.commandId === PORTAL_CMD_NOTIFY_PAYLOAD && p.isResponse === 0 && p.channel === channel && p.cmd === innerCmd && typeof d?.payload === "object" && d.payload !== null;
24098
+ if (!acknowledgement && !notification)
24099
+ return;
24100
+ cleanup();
24101
+ if (acknowledgement && p.errCode !== 0) {
24102
+ reject(new Error(`rtc: ${sn} rejected cmd ${innerCmd} (err ${p.errCode})`));
24103
+ } else {
24104
+ this.deps.logger?.debug?.(`[rtc] ${sn} cmd ${innerCmd} acked`);
24105
+ resolve();
24106
+ }
24107
+ };
24108
+ const onClose = () => {
24109
+ cleanup();
24110
+ reject(new Error(`rtc: ${sn} session closed while waiting for cmd ${innerCmd} ACK`));
24111
+ };
24112
+ const timer = setTimeout(() => {
24113
+ cleanup();
24114
+ reject(new Error(`rtc: ${sn} cmd ${innerCmd} ACK timed out after ${ACK_TIMEOUT_MS}ms`));
24115
+ }, ACK_TIMEOUT_MS);
24116
+ const cleanup = () => {
24117
+ clearTimeout(timer);
24118
+ st.session.off("commandData", onData);
24119
+ st.session.off("close", onClose);
24120
+ this.touch(sn, st);
24121
+ };
24122
+ st.session.on("commandData", onData);
24123
+ st.session.on("close", onClose);
24124
+ if (!st.session.sendCommand(packet)) {
24125
+ cleanup();
24126
+ reject(new Error(`rtc: ${sn} command channel not open, cmd ${innerCmd} not sent`));
24127
+ }
24128
+ });
24129
+ }
24130
+ async stationSession(route, adminUserId, identity) {
24131
+ const sn = route.stationSn;
24132
+ const existing = this.sessions.get(sn);
24133
+ if (existing) {
24134
+ await existing.ready;
24135
+ if (existing.session.isConnected) {
24136
+ this.touch(sn, existing);
24137
+ return existing;
24138
+ }
24139
+ this.drop(sn, existing);
24140
+ }
24141
+ const session = (this.deps.createSession ?? ((o) => new RtcSession(o)))({
24142
+ authToken: identity.authToken,
24143
+ gtoken: identity.gtoken,
24144
+ stationSn: sn,
24145
+ adminUserId,
24146
+ shard: this.deps.shard(),
24147
+ country: this.deps.country ?? "US",
24148
+ logger: this.deps.logger,
24149
+ signalingMode: route.signalingMode,
24150
+ peer: { logger: this.deps.logger, iceTransportPolicy: route.iceTransportPolicy }
24151
+ });
24152
+ const ready = this.bringUp(sn, session);
24153
+ const st = { session, seg: new SegmentCounter(), ready, queue: Promise.resolve(), leases: 0 };
24154
+ session.on("error", (e) => this.deps.onError?.(e));
24155
+ session.on("close", () => {
24156
+ if (this.sessions.get(sn) === st)
24157
+ this.sessions.delete(sn);
24158
+ });
24159
+ this.sessions.set(sn, st);
24160
+ try {
24161
+ await ready;
24162
+ } catch (e) {
24163
+ this.drop(sn, st);
24164
+ throw e;
24165
+ }
24166
+ this.touch(sn, st);
24167
+ return st;
24168
+ }
24169
+ /**
24170
+ * One bounded bring-up: the session is up when its command channel opens, and it fails, with the
24171
+ * session closed and every listener gone, when `connect()` throws, the session closes first, or
24172
+ * {@link CONNECT_TIMEOUT_MS} passes. A single promise, so an early failure cannot leave a second one
24173
+ * rejecting unheard.
24174
+ */
24175
+ bringUp(sn, session) {
24176
+ return new Promise((resolve, reject) => {
24177
+ let settled = false;
24178
+ const finish = (err) => {
24179
+ if (settled)
24180
+ return;
24181
+ settled = true;
24182
+ clearTimeout(timer);
24183
+ session.off("connected", onConnected);
24184
+ session.off("close", onClose);
24185
+ if (err) {
24186
+ try {
24187
+ session.close();
24188
+ } catch {
24189
+ }
24190
+ reject(err);
24191
+ } else {
24192
+ this.deps.logger?.info?.(`[rtc] ${sn} command channel up`);
24193
+ resolve();
24194
+ }
24195
+ };
24196
+ const onConnected = () => finish();
24197
+ const onClose = () => finish(new Error(`rtc: ${sn} session closed before the command channel opened`));
24198
+ const timer = setTimeout(() => finish(new Error(`rtc: ${sn} did not come up within ${CONNECT_TIMEOUT_MS2}ms`)), CONNECT_TIMEOUT_MS2);
24199
+ session.once("connected", onConnected);
24200
+ session.once("close", onClose);
24201
+ Promise.resolve().then(() => session.connect()).catch((e) => finish(e instanceof Error ? e : new Error(String(e))));
24202
+ });
24203
+ }
24204
+ touch(sn, st) {
24205
+ if (st.idle)
24206
+ clearTimeout(st.idle);
24207
+ if (st.leases > 0)
24208
+ return;
24209
+ st.idle = setTimeout(() => this.drop(sn, st), IDLE_CLOSE_MS);
24210
+ st.idle.unref?.();
24211
+ }
24212
+ drop(sn, st) {
24213
+ if (st.idle)
24214
+ clearTimeout(st.idle);
24215
+ if (this.sessions.get(sn) === st)
24216
+ this.sessions.delete(sn);
24217
+ try {
24218
+ st.session.close();
24219
+ } catch {
24220
+ }
24221
+ }
24222
+ };
24223
+
24224
+ // dist/transport/mqtt/command-router.js
24225
+ import { randomBytes as randomBytes3 } from "node:crypto";
24226
+
24227
+ // dist/transport/mqtt/broker-discovery.js
24228
+ import { resolve4 } from "node:dns/promises";
24229
+ async function resolveBrokerIps(hostname) {
24230
+ try {
24231
+ return await resolve4(hostname);
24232
+ } catch {
24233
+ return [];
24234
+ }
24235
+ }
24236
+ function mergeCandidateIps(dnsIps, extraIps = []) {
24237
+ return Array.from(/* @__PURE__ */ new Set([...dnsIps, ...extraIps]));
24238
+ }
24239
+ function rankResults(results) {
24240
+ return [...results].sort((a, b) => Number(b.granted) - Number(a.granted));
24241
+ }
24242
+ async function probeBrokerInstance(ip, creds, opts) {
24243
+ const mqtt = await loadMqtt();
24244
+ const start = Date.now();
24245
+ const timeoutMs = opts.timeoutMs ?? 8e3;
24246
+ return await new Promise((resolvePromise) => {
24247
+ let settled = false;
24248
+ const finish = (r) => {
24249
+ if (settled)
24250
+ return;
24251
+ settled = true;
24252
+ clearTimeout(timer);
24253
+ try {
24254
+ client.end(true);
24255
+ } catch {
24256
+ }
24257
+ resolvePromise({ ip, ms: Date.now() - start, ...r });
24258
+ };
24259
+ const client = mqtt.connect({
24260
+ host: ip,
24261
+ port: creds.port ?? 8883,
24262
+ protocol: "mqtts",
24263
+ ...bareIpTlsOptions({
24264
+ hostname: creds.hostname,
24265
+ cert: creds.certificate_pem,
24266
+ key: creds.private_key,
24267
+ ca: creds.aws_root_ca1_pem
24268
+ }),
24269
+ clientId: opts.clientId,
24270
+ protocolVersion: 4,
24271
+ keepalive: 60,
24272
+ clean: true,
24273
+ reconnectPeriod: 0,
24274
+ connectTimeout: timeoutMs
24275
+ });
24276
+ const timer = setTimeout(() => finish({ granted: false, error: "timeout" }), timeoutMs);
24277
+ client.on("connect", () => {
24278
+ client.subscribe(opts.topic, { qos: 1 }, (err, granted) => {
24279
+ if (err)
24280
+ return finish({ granted: false, error: err.message });
24281
+ const g = granted?.[0];
24282
+ const denied = !g || g.qos === 128;
24283
+ finish({ granted: !denied, grantedQos: g?.qos });
24284
+ });
24285
+ });
24286
+ client.on("error", (err) => finish({ granted: false, error: err.message }));
24287
+ });
24288
+ }
24289
+ async function discoverReachableInstance(creds, opts) {
24290
+ const dnsIps = await resolveBrokerIps(creds.hostname);
24291
+ const all = mergeCandidateIps(dnsIps, opts.candidateIps);
24292
+ const results = [];
24293
+ for (const ip of all) {
24294
+ const r = await probeBrokerInstance(ip, creds, {
24295
+ clientId: opts.clientIdFor(ip),
24296
+ topic: opts.topic,
24297
+ timeoutMs: opts.perAttemptTimeoutMs
24298
+ });
24299
+ results.push(r);
24300
+ if (r.granted && opts.stopOnFirstGrant)
24301
+ break;
24302
+ }
24303
+ return rankResults(results);
24304
+ }
24305
+
24306
+ // dist/transport/dp-preset.js
24307
+ var RGBCW_CH = {
24308
+ R: [15.932, 0.7035, 0.294],
24309
+ G: [39.83, 0.1629, 0.7208],
24310
+ B: [2.2404, 0.1472, 0.0309],
24311
+ W: [66.28, 0.4681, 0.4182],
24312
+ C: [73.58, 0.3166, 0.3397]
24313
+ };
24314
+ var RGBCW_X = Object.fromEntries(Object.entries(RGBCW_CH).map(([k, [Y, x, y]]) => [k, [x * Y / y, Y, (1 - x - y) * Y / y]]));
24315
+ var RGB_HEX = /^[0-9a-fA-F]{6}$/;
22452
24316
  var RGBCW_GAMMA = 2.2;
22453
24317
  var RGBCW_SAT = 1.65;
22454
24318
  var dec = (b) => Math.pow(b / 255, RGBCW_GAMMA);
@@ -22660,10 +24524,10 @@ function dpColorFields(spec) {
22660
24524
  }
22661
24525
 
22662
24526
  // dist/transport/mqtt/clean-codec.js
22663
- import { randomUUID as randomUUID2 } from "node:crypto";
24527
+ import { randomUUID as randomUUID3 } from "node:crypto";
22664
24528
  function buildCleanDpEnvelope(accountId, deviceSn, dp, value, opts) {
22665
24529
  const payload = JSON.stringify({
22666
- t: opts?.uuid ?? randomUUID2(),
24530
+ t: opts?.uuid ?? randomUUID3(),
22667
24531
  protocol: 2,
22668
24532
  account_id: accountId,
22669
24533
  device_sn: deviceSn,
@@ -23350,7 +25214,7 @@ function deriveTuyaAccount(eufyUserId, phoneCode) {
23350
25214
  }
23351
25215
 
23352
25216
  // dist/transport/tuya/sign.js
23353
- import { createHash as createHash5, createHmac as createHmac3 } from "node:crypto";
25217
+ import { createHash as createHash5, createHmac as createHmac4 } from "node:crypto";
23354
25218
  var SIGN_ALLOWLIST = /* @__PURE__ */ new Set([
23355
25219
  "a",
23356
25220
  "v",
@@ -23393,7 +25257,7 @@ var HmacSigner = class {
23393
25257
  this.key = key ?? process.env.TUYA_SIGN_KEY ?? TUYA_SIGN_K;
23394
25258
  }
23395
25259
  sign(preimage) {
23396
- return createHmac3("sha256", this.key).update(preimage, "utf-8").digest("hex");
25260
+ return createHmac4("sha256", this.key).update(preimage, "utf-8").digest("hex");
23397
25261
  }
23398
25262
  };
23399
25263
  var TUYA_CHKEY = "7cbfe6d8";
@@ -23402,7 +25266,7 @@ var TUYA_CHKEY = "7cbfe6d8";
23402
25266
  import { randomBytes as randomBytes4, createHash as createHash6, createPublicKey, publicEncrypt, constants as constants2 } from "node:crypto";
23403
25267
 
23404
25268
  // dist/transport/tuya/request.js
23405
- import { randomUUID as randomUUID3 } from "node:crypto";
25269
+ import { randomUUID as randomUUID4 } from "node:crypto";
23406
25270
  var TUYA_API_ENDPOINT = "https://a1.tuyaeu.com/api.json";
23407
25271
  var TUYA_APP_KEY = "w8x4ppqkdxvqnd73ahj9";
23408
25272
  var TUYA_APP_SECRET = "pt585qhmt75hwcynchnps9dnxh9suhwd";
@@ -23434,7 +25298,7 @@ function buildApiParams(action, opts) {
23434
25298
  a: action.a,
23435
25299
  v: action.v,
23436
25300
  time: String(opts.time ?? Math.floor(Date.now() / 1e3)),
23437
- requestId: opts.requestId ?? randomUUID3(),
25301
+ requestId: opts.requestId ?? randomUUID4(),
23438
25302
  sid: opts.session.sid,
23439
25303
  deviceId: opts.session.deviceId,
23440
25304
  chKey: opts.session.chKey,
@@ -23971,7 +25835,7 @@ async function resolveLightEffect(mega, lightId) {
23971
25835
  }
23972
25836
 
23973
25837
  // dist/transport/push/push-client.js
23974
- import { EventEmitter as EventEmitter8 } from "node:events";
25838
+ import { EventEmitter as EventEmitter12 } from "node:events";
23975
25839
  import tls2 from "node:tls";
23976
25840
 
23977
25841
  // dist/transport/push/proto.js
@@ -24226,7 +26090,7 @@ var MessageTag;
24226
26090
  })(MessageTag || (MessageTag = {}));
24227
26091
 
24228
26092
  // dist/transport/push/parser.js
24229
- import { EventEmitter as EventEmitter7 } from "node:events";
26093
+ import { EventEmitter as EventEmitter11 } from "node:events";
24230
26094
  var State;
24231
26095
  (function(State2) {
24232
26096
  State2[State2["VERSION_TAG_AND_SIZE"] = 0] = "VERSION_TAG_AND_SIZE";
@@ -24244,7 +26108,7 @@ var TAG_TO_TYPE = {
24244
26108
  [MessageTag.DataMessageStanza]: "mcs_proto.DataMessageStanza",
24245
26109
  [MessageTag.StreamErrorStanza]: "mcs_proto.StreamErrorStanza"
24246
26110
  };
24247
- var McsParser = class extends EventEmitter7 {
26111
+ var McsParser = class extends EventEmitter11 {
24248
26112
  data = Buffer.alloc(0);
24249
26113
  state = State.VERSION_TAG_AND_SIZE;
24250
26114
  messageTag = 0;
@@ -24422,7 +26286,7 @@ function normalizePushEvent(raw) {
24422
26286
  raw
24423
26287
  };
24424
26288
  }
24425
- var PushClient = class _PushClient extends EventEmitter8 {
26289
+ var PushClient = class _PushClient extends EventEmitter12 {
24426
26290
  creds;
24427
26291
  logger;
24428
26292
  /** Consecutive MCS login rejections tolerated (self-healing propagation) before surfacing an error. */
@@ -25012,7 +26876,14 @@ function deviceClassOf(codec, realtime) {
25012
26876
  const cls = CLASS_BY_CODEC[codec];
25013
26877
  return cls === "camera" && realtime !== "p2p" ? "other" : cls;
25014
26878
  }
26879
+ function recordName(raw, deviceClass) {
26880
+ if (deviceClass === "vacuum") {
26881
+ return raw.alias_name || raw.device_alias_name || raw.device_name || void 0;
26882
+ }
26883
+ return raw.device_name ?? raw.device_alias_name ?? raw.alias_name;
26884
+ }
25015
26885
  var LIST_REUSE_MS = 5e3;
26886
+ var CLOUD_DPS_MODELS = /* @__PURE__ */ new Set(["T2351"]);
25016
26887
  var DeviceRegistry = class {
25017
26888
  mega;
25018
26889
  onError;
@@ -25037,6 +26908,8 @@ var DeviceRegistry = class {
25037
26908
  overlayRefusalReported = false;
25038
26909
  /** Per-serial capability cache for {@link capabilitiesForDevice}; `null` = negative hit. */
25039
26910
  deviceCapsCache = /* @__PURE__ */ new Map();
26911
+ /** Per-serial cloud data points of an AIoT robot, joined beneath the params in {@link record} — see {@link loadCloudDps}. */
26912
+ cloudDps = /* @__PURE__ */ new Map();
25040
26913
  /** Per-serial realtime state, keyed by param id in the device's own namespace (see {@link DeviceRecord.dpParams}). */
25041
26914
  dpParams = /* @__PURE__ */ new Map();
25042
26915
  /** Callers blocked in {@link awaitRealtimeState}, released by the device's first report. */
@@ -25131,21 +27004,24 @@ var DeviceRegistry = class {
25131
27004
  category: raw.category,
25132
27005
  params
25133
27006
  }).codec;
27007
+ const deviceClass = deviceClassOf(codec, c.realtime);
25134
27008
  seen.set(raw.device_sn, {
25135
27009
  sn: raw.device_sn,
25136
- name: raw.device_name ?? raw.device_alias_name ?? raw.alias_name,
27010
+ name: recordName(raw, deviceClass),
25137
27011
  model: raw.device_model,
25138
27012
  stationSn: resolvedStationSn(raw, raw.device_sn),
27013
+ ...typeof raw.device_channel === "number" ? { channel: raw.device_channel } : {},
25139
27014
  p2pDid: raw.p2p_did,
25140
27015
  params,
25141
27016
  paramUpdatedAt,
25142
27017
  lastSeenMs: lastSeenMsOf(paramUpdatedAt),
25143
27018
  raw,
25144
- deviceClass: deviceClassOf(codec, c.realtime),
27019
+ deviceClass,
25145
27020
  ...c
25146
27021
  });
25147
27022
  }
25148
27023
  }
27024
+ await this.loadCloudDps(seen);
25149
27025
  this.lastRefreshPartial = partial;
25150
27026
  if (partial) {
25151
27027
  for (const prev of this.devices)
@@ -25236,9 +27112,46 @@ var DeviceRegistry = class {
25236
27112
  }
25237
27113
  return dev;
25238
27114
  }
27115
+ /**
27116
+ * Hold an AIoT robot's cloud data points: the cloud's last-known value of each one it has reported,
27117
+ * from `getDeviceRelationList`'s per-device `dps`.
27118
+ *
27119
+ * The device list carries only some of a robot's data points, so a point the robot publishes on change
27120
+ * alone (its scene list, its schedules, its consumables) has no value until it next reports. The
27121
+ * relation list holds every one, for an account the robot is shared with as well as its owner.
27122
+ *
27123
+ * Kept apart from the device list's params rather than merged into them: those are what a poll diffs,
27124
+ * and a diff retires the realtime report for that id, so a cloud value lagging the robot's last report
27125
+ * would replace it. {@link record} joins this beneath both halves. A failure keeps what was held.
27126
+ *
27127
+ * Limited to {@link CLOUD_DPS_MODELS}, the models whose relation-list `dps` are checked to carry the
27128
+ * DP numbers their realtime reports use.
27129
+ */
27130
+ async loadCloudDps(seen) {
27131
+ const robots = [...seen.values()].filter((d) => CLOUD_DPS_MODELS.has(d.model ?? ""));
27132
+ if (!robots.length)
27133
+ return;
27134
+ let res;
27135
+ try {
27136
+ res = await this.mega.getDeviceRelationList();
27137
+ } catch (e) {
27138
+ if (e instanceof SessionExpiredError)
27139
+ throw e;
27140
+ this.logger.debug(`[registry] device relation list unavailable: ${e?.message ?? e}`);
27141
+ return;
27142
+ }
27143
+ const wanted = new Set(robots.map((d) => d.sn));
27144
+ for (const entry of res.devices ?? []) {
27145
+ const sn = entry?.device?.device_sn;
27146
+ const dps = parseAiotDpReport({ payload: entry?.device?.dps });
27147
+ if (sn && wanted.has(sn) && dps)
27148
+ this.cloudDps.set(sn, dps);
27149
+ }
27150
+ }
25239
27151
  /**
25240
27152
  * Resolve a serial to a {@link DeviceRecord} with current params: starts from the device-list params, then
25241
- * overlays a fresh `get_device_param_list` when that call is available to this account.
27153
+ * overlays a fresh `get_device_param_list` when that call is available to this account. An AIoT robot's
27154
+ * cloud data points ({@link loadCloudDps}) sit beneath both, filling only ids neither carries.
25242
27155
  *
25243
27156
  * The overlay is **owner-gated** — a shared or member account is refused it for every device, permanently,
25244
27157
  * which {@link OWNER_ONLY_CODE} identifies — so when it is unavailable the device list is the source
@@ -25267,7 +27180,7 @@ var DeviceRegistry = class {
25267
27180
  let dev = this.devices.find((d) => d.sn === sn);
25268
27181
  if (!dev)
25269
27182
  throw new Error(`device ${sn} not found (have: ${this.devices.map((d) => d.sn).join(", ")})`);
25270
- const params = { ...dev.params ?? {} };
27183
+ const params = { ...this.cloudDps.get(sn), ...dev.params ?? {} };
25271
27184
  const paramUpdatedAt = { ...dev.paramUpdatedAt ?? {} };
25272
27185
  if (!this.overlayRefused.has(sn)) {
25273
27186
  try {
@@ -25560,6 +27473,8 @@ function tuyaDevIdFrom(raw) {
25560
27473
  var DEFAULT_POLL_MS = 6e5;
25561
27474
  var DEFAULT_PREWARM_TIERS = ["wired", "battery"];
25562
27475
  var SESSION_RECYCLE_WAIT_MS = 5e3;
27476
+ var PUSH_RETRY_MIN_MS = 3e4;
27477
+ var PUSH_RETRY_MAX_MS = 6e5;
25563
27478
  var RealtimeStartupSupersededError = class extends Error {
25564
27479
  };
25565
27480
  var RefreshWindowClosedError = class extends Error {
@@ -25575,7 +27490,7 @@ function readinessSnapshot(readiness, state = readiness.state) {
25575
27490
  wiredP2p: Object.freeze({ ...readiness.wiredP2p })
25576
27491
  });
25577
27492
  }
25578
- var EufyMega = class extends EventEmitter9 {
27493
+ var EufyMega = class extends EventEmitter13 {
25579
27494
  opts;
25580
27495
  mega;
25581
27496
  /**
@@ -25635,6 +27550,8 @@ var EufyMega = class extends EventEmitter9 {
25635
27550
  prewarmTiers;
25636
27551
  /** Transport-side owner of the P2P sessions + all wire senders. */
25637
27552
  p2p;
27553
+ /** Transport-side owner of the T9000 station sessions (sibling of {@link p2p}). */
27554
+ rtc;
25638
27555
  /** Transport-side owner of the secure-MQTT ff09 lock/garage command path (sibling of {@link p2p}). */
25639
27556
  mqtt;
25640
27557
  /** Transport-side owner of the legacy Tuya REST command path for non-AIoT vacuums (G-series). */
@@ -25656,6 +27573,8 @@ var EufyMega = class extends EventEmitter9 {
25656
27573
  mapStores = /* @__PURE__ */ new Map();
25657
27574
  /** Re-armed after each cloud-param poll; cancelled by {@link disconnect}. */
25658
27575
  pollTimer = new Timer();
27576
+ /** Armed while a failed push bring-up waits to be retried; cancelled by {@link disconnect}. */
27577
+ pushRetryTimer = new Timer();
25659
27578
  constructor(opts) {
25660
27579
  super();
25661
27580
  this.opts = opts;
@@ -25695,6 +27614,14 @@ var EufyMega = class extends EventEmitter9 {
25695
27614
  onLevel2Ready: (sn, cipherId) => this.emit("p2pLevel2Ready", { stationSn: sn, cipherId }),
25696
27615
  onFrame: (stationSn, f) => this.onP2PFrame(stationSn, f)
25697
27616
  });
27617
+ this.rtc = new RtcCommandRouter({
27618
+ identity: () => this.mega.rtcIdentity(),
27619
+ shard: () => this.mega.rtcShard,
27620
+ country: opts.countryCode,
27621
+ logger: opts.logger,
27622
+ ffmpegPath: opts.ffmpegPath,
27623
+ onError: (e) => this.reportError(e)
27624
+ });
25698
27625
  this.mqtt = new MqttCommandRouter({
25699
27626
  mega: this.mega,
25700
27627
  logger: opts.logger,
@@ -25960,13 +27887,22 @@ var EufyMega = class extends EventEmitter9 {
25960
27887
  *
25961
27888
  * The evidence set is widened, never replaced: the ids come back through the cloud record, and a
25962
27889
  * record that omits a realtime-only id would otherwise un-know it and re-trigger on the next report.
27890
+ *
27891
+ * The device is re-resolved against the fresh record before binding. A property gated on a
27892
+ * realtime-only param enters the schema only once that param is evidence, and the value that made it
27893
+ * evidence was stored before the property existed, so the record's realtime params are applied again
27894
+ * to land it under the property's name.
25963
27895
  */
25964
27896
  async rebindReads(sn) {
25965
27897
  const dev = this.liveDevices.get(sn)?.deref();
25966
27898
  if (!dev)
25967
27899
  return;
25968
27900
  try {
25969
- const ctx = await this.commandContext(sn);
27901
+ const rec = await this.registry.record(sn);
27902
+ dev.reresolve(rec);
27903
+ if (rec.dpParams)
27904
+ this.applyAndAnnounce(dev, rec.dpParams);
27905
+ const ctx = await this.commandContext(sn, rec);
25970
27906
  dev.bindActions(ctx, this.commandSinkFor(sn), this.mediaProviderFor(sn), this.ff09SettingsReaderFor(sn, ctx), rawDpCodec);
25971
27907
  this.boundParamIds.set(sn, /* @__PURE__ */ new Set([...this.boundParamIds.get(sn) ?? [], ...ctx.paramIds]));
25972
27908
  this.emit("deviceState", this.deviceState(sn));
@@ -26026,6 +27962,8 @@ var EufyMega = class extends EventEmitter9 {
26026
27962
  * only "differs from what was read before", which state already on hand can satisfy spuriously — and the
26027
27963
  * caller that has no expectation is the push path, where the signal itself is the news that a re-read is owed.
26028
27964
  *
27965
+ * Only a write's observation throws at the deadline; a push with nothing moved answers `false`.
27966
+ *
26029
27967
  * The cloud half is asked for through {@link DeviceRegistry.refreshedList}, never by fetching the account
26030
27968
  * list outright. The fetch is account-wide — one house list plus one device list per house — so a param that
26031
27969
  * never converges would otherwise spend a whole burst of those every iteration of this loop, and concurrent
@@ -26076,6 +28014,8 @@ var EufyMega = class extends EventEmitter9 {
26076
28014
  if (refresh.expected !== void 0 && settled())
26077
28015
  return true;
26078
28016
  }
28017
+ if (refresh.expected === void 0)
28018
+ return false;
26079
28019
  throw new StateConvergenceError({
26080
28020
  sn,
26081
28021
  property: refresh.property,
@@ -26381,6 +28321,28 @@ var EufyMega = class extends EventEmitter9 {
26381
28321
  }
26382
28322
  };
26383
28323
  }
28324
+ /**
28325
+ * The station a device's commands go through: the device itself, or the HomeBase the registry links it
28326
+ * to. Answers the target record, the station record and serial, the station's `device_type`, and the
28327
+ * `t9000` / `t8n00` family flags.
28328
+ */
28329
+ stationOf(sn) {
28330
+ const devices = this.registry.list();
28331
+ const target = devices.find((d) => d.sn === sn);
28332
+ const stationSn = target?.stationSn || sn;
28333
+ const station = devices.find((d) => d.sn === stationSn);
28334
+ const raw = station?.raw ?? {};
28335
+ const deviceType = typeof raw.device_type === "number" ? raw.device_type : void 0;
28336
+ const family = { deviceType, model: station?.model };
28337
+ return { target, station, stationSn, raw, deviceType, t9000: isStation9000(family), t8n00: isNvrT8N00(family) };
28338
+ }
28339
+ /** The vendor DeviceType of the station a device hangs off; `undefined` for a station itself. */
28340
+ stationDeviceTypeOf(sn) {
28341
+ const st = this.stationOf(sn);
28342
+ if (!st.station || st.stationSn === sn)
28343
+ return void 0;
28344
+ return st.deviceType;
28345
+ }
26384
28346
  /**
26385
28347
  * Combine explicit P2P media with the optional passive push-thumbnail provider.
26386
28348
  *
@@ -26391,7 +28353,7 @@ var EufyMega = class extends EventEmitter9 {
26391
28353
  * current. With nothing retained the refusal stands.
26392
28354
  */
26393
28355
  mediaProviderFor(sn) {
26394
- const media = this.p2p.mediaProviderFor(sn);
28356
+ const media = this.rtcMediaFor(sn) ?? this.p2p.mediaProviderFor(sn);
26395
28357
  const cache = this.storedImages;
26396
28358
  if (!cache)
26397
28359
  return media;
@@ -26428,8 +28390,10 @@ var EufyMega = class extends EventEmitter9 {
26428
28390
  * The `eufy_life` DP writes (smart lights) are secure-MQTT-only. `aiot-dp` routes to either the
26429
28391
  * Anker AIoT MQTT stack or the legacy Tuya REST router depending on the device's category
26430
28392
  * (`eufy_home_tuya` → Tuya, everything else → MQTT). The capability layer emits a single `aiot-dp`
26431
- * kind and stays transport-agnostic; only the facade sees both sides and decides here. Everything
26432
- * else is P2P.
28393
+ * kind and stays transport-agnostic; only the facade sees both sides and decides here. A T9000 or T8N00
28394
+ * station and the devices attached to it go over RTC, with an attached device's command refused
28395
+ * unless its channel resolves back to it on the station. T8N00 uses full SDP and admits direct and
28396
+ * relay candidates; T9000 retains compact SDP and relay-only candidates. Everything else is P2P.
26433
28397
  */
26434
28398
  routeCommand(sn, cmd) {
26435
28399
  if (cmd.kind === "ff09-actuate" || cmd.kind === "ff09-autolock" || cmd.kind === "ff09-setting-toggle") {
@@ -26449,8 +28413,42 @@ var EufyMega = class extends EventEmitter9 {
26449
28413
  return this.tuya.dispatchCommand(sn, cmd);
26450
28414
  return this.mqtt.dispatchCommand(sn, cmd);
26451
28415
  }
28416
+ const route = this.rtcRouteFor(sn);
28417
+ if (route) {
28418
+ if (route.attached && this.registry.serialForFrame(route.stationSn, cmd.channel) !== sn)
28419
+ return Promise.reject(new Error("RTC command requires an unambiguous attached-device channel"));
28420
+ return this.rtc.dispatchCommand(route, cmd);
28421
+ }
26452
28422
  return this.p2p.dispatchCommand(sn, cmd);
26453
28423
  }
28424
+ /**
28425
+ * The RTC route for a T9000 or T8N00 station or a device attached to one, decided by the station's model
28426
+ * classification; `undefined` for any other device. A T8N00 route carries its native `call` signalling. The admin id is the station's
28427
+ * `member.admin_user_id`, else the logged-in user.
28428
+ */
28429
+ rtcRouteFor(sn) {
28430
+ const { target, station, stationSn, raw, t9000, t8n00: native } = this.stationOf(sn);
28431
+ if (!target || !station || !(t9000 || native))
28432
+ return void 0;
28433
+ const member = raw.member?.admin_user_id;
28434
+ const adminUserId = typeof member === "string" && member ? member : void 0;
28435
+ const base = { stationSn, adminUserId, attached: stationSn !== sn };
28436
+ return native ? { ...base, signalingMode: "call", iceTransportPolicy: "all" } : base;
28437
+ }
28438
+ /**
28439
+ * The RTC media provider for a camera attached to a T9000 whose `device_channel` resolves back to it on
28440
+ * the station; `undefined` otherwise, including a camera behind a T8N00, whose route carries commands only.
28441
+ */
28442
+ rtcMediaFor(sn) {
28443
+ const route = this.rtcRouteFor(sn);
28444
+ if (!route?.attached || route.signalingMode === "call")
28445
+ return void 0;
28446
+ const raw = this.registry.list().find((d) => d.sn === sn)?.raw ?? {};
28447
+ const channel = typeof raw.device_channel === "number" ? raw.device_channel : void 0;
28448
+ if (channel === void 0 || this.registry.serialForFrame(route.stationSn, channel) !== sn)
28449
+ return void 0;
28450
+ return this.rtc.mediaProviderFor({ ...route, cameraSn: sn, channel });
28451
+ }
26454
28452
  /**
26455
28453
  * List + classify devices across all houses (mega API). Each device is tagged with its API backend
26456
28454
  * + realtime transport. Camera/HomeBase records still appear here for inventory; driving them is
@@ -26683,13 +28681,38 @@ var EufyMega = class extends EventEmitter9 {
26683
28681
  this.schedulePoll();
26684
28682
  const failures = readiness.push.failed + readiness.mqtt.failed + readiness.wiredP2p.failed;
26685
28683
  this.settleRealtimeGeneration(generation, failures || startupFailed ? "partial" : "ready");
28684
+ if (readiness.push.failed)
28685
+ this.retryPush(generation);
26686
28686
  } catch (e) {
26687
28687
  this.reportError(e);
26688
28688
  readiness.push.failed += readiness.push.pending;
26689
28689
  readiness.push.pending = 0;
26690
28690
  this.settleRealtimeGeneration(generation, epoch === this.realtimeEpoch ? "partial" : "superseded");
28691
+ if (epoch === this.realtimeEpoch)
28692
+ this.retryPush(generation);
26691
28693
  }
26692
28694
  }
28695
+ /**
28696
+ * Bring push up again after the generation's startup attempt failed, backing off between attempts
28697
+ * until one connects, the generation is superseded, or it is aborted by {@link disconnect}.
28698
+ *
28699
+ * The MCS socket reconnects on its own only once it has connected. The settled
28700
+ * {@link RealtimeReadiness} is a startup snapshot and is not revised when a retry connects.
28701
+ */
28702
+ retryPush(generation, delayMs = PUSH_RETRY_MIN_MS) {
28703
+ this.pushRetryTimer.arm(delayMs, () => {
28704
+ this.startPush(generation.abort.signal).then((client) => {
28705
+ if (generation.epoch !== this.realtimeEpoch)
28706
+ return client.close();
28707
+ this.pushClient = client;
28708
+ }, (error) => {
28709
+ if (generation.epoch !== this.realtimeEpoch)
28710
+ return;
28711
+ this.reportError(error);
28712
+ this.retryPush(generation, Math.min(delayMs * 2, PUSH_RETRY_MAX_MS));
28713
+ });
28714
+ });
28715
+ }
26693
28716
  /** Resolve a generation with an immutable count snapshot; later transport completions are ignored. */
26694
28717
  settleRealtimeGeneration(generation, state) {
26695
28718
  if (generation.settled)
@@ -27287,16 +29310,20 @@ var EufyMega = class extends EventEmitter9 {
27287
29310
  await this.commandSinkFor(sn).dispatch(cmd);
27288
29311
  }
27289
29312
  /**
27290
- * Restart a HomeBase.
29313
+ * Restart a station: a HomeBase, or a camera-family device that is its own station.
27291
29314
  *
27292
- * **HomeBases only** — restart is a hub operation, so a non-HomeBase serial (a camera, an NVR)
27293
- * throws rather than doing nothing. The hub drops its connection and returns after a minute or two,
27294
- * so everything behind it is briefly offline. Verified on real hardware.
29315
+ * The restart is `RESTART_HUB` on the station's broadcast channel, so it reaches whatever owns the
29316
+ * P2P session. A standalone camera or doorbell owns its own session and is the station it restarts.
29317
+ * A camera attached to a HomeBase is not — the same frame would restart its HomeBase — so its serial
29318
+ * throws, as does any non-camera serial, rather than doing nothing. The device drops its connection
29319
+ * and returns after a minute or two; a HomeBase takes everything behind it offline meanwhile.
29320
+ * Verified on real hardware against a HomeBase and a standalone indoor camera.
27295
29321
  */
27296
29322
  async reboot(sn) {
27297
29323
  const ctx = await this.commandContext(sn);
27298
- if (!isHomeBase({ deviceType: ctx.deviceType, model: ctx.model })) {
27299
- throw new Error(`reboot: ${sn} is not a HomeBase (deviceType ${ctx.deviceType ?? "?"}, model ${ctx.model ?? "?"}) \u2014 restart is a hub-only operation`);
29324
+ const standaloneCamera = ctx.codec === "camera" && this.p2p.stationKeyOf(sn) === sn;
29325
+ if (!isHomeBase({ deviceType: ctx.deviceType, model: ctx.model }) && !standaloneCamera) {
29326
+ throw new Error(`reboot: ${sn} is neither a HomeBase nor a standalone camera (deviceType ${ctx.deviceType ?? "?"}, model ${ctx.model ?? "?"}) \u2014 restart addresses the station that owns the P2P session`);
27300
29327
  }
27301
29328
  await this.p2p.rebootStation(sn);
27302
29329
  }
@@ -27328,8 +29355,9 @@ var EufyMega = class extends EventEmitter9 {
27328
29355
  return EMPTY_DP_CATALOG;
27329
29356
  }
27330
29357
  }
27331
- async commandContext(sn) {
27332
- const rec = await this.registry.record(sn);
29358
+ /** The {@link CommandContext} for a device, built from `known` when that record is already in hand. */
29359
+ async commandContext(sn, known) {
29360
+ const rec = known ?? await this.registry.record(sn);
27333
29361
  const dev = this.registry.require(sn);
27334
29362
  const raw = dev.raw ?? {};
27335
29363
  const rawChannel = raw.device_channel;
@@ -27366,6 +29394,7 @@ var EufyMega = class extends EventEmitter9 {
27366
29394
  hasP2p: P2PCommandRouter.claimsDevice(dev),
27367
29395
  // Topology as the record states it: a parent that isn't the device itself means HomeBase-attached.
27368
29396
  homeBaseAttached: !!raw.parent_sn && raw.parent_sn !== dev.sn,
29397
+ stationDeviceType: this.stationDeviceTypeOf(sn),
27369
29398
  dpCatalog
27370
29399
  };
27371
29400
  }
@@ -27540,8 +29569,10 @@ var EufyMega = class extends EventEmitter9 {
27540
29569
  */
27541
29570
  async teardownRealtime() {
27542
29571
  this.pollTimer.cancel();
29572
+ this.pushRetryTimer.cancel();
27543
29573
  this.lastStateAnnounced.clear();
27544
29574
  await this.closeMqttTransports();
29575
+ this.rtc.close();
27545
29576
  await this.p2p.closeAll();
27546
29577
  this.pushClient?.close();
27547
29578
  this.pushClient = void 0;
@@ -28046,7 +30077,7 @@ var SolixClient = class _SolixClient {
28046
30077
  };
28047
30078
 
28048
30079
  // dist/transport/mqtt/solix-mqtt.js
28049
- import { EventEmitter as EventEmitter10 } from "node:events";
30080
+ import { EventEmitter as EventEmitter14 } from "node:events";
28050
30081
  var SOLIX_METER_FIELD_NAMES = {
28051
30082
  168: "meterPowerL1",
28052
30083
  // Anker Modbus: primary_phase_1_active_power
@@ -28224,7 +30255,7 @@ function addSolarbankScalars(frame, out) {
28224
30255
  out.gridExportLimit = df.readUInt16LE(5);
28225
30256
  }
28226
30257
  }
28227
- var SolixMqtt = class extends EventEmitter10 {
30258
+ var SolixMqtt = class extends EventEmitter14 {
28228
30259
  transport;
28229
30260
  appName;
28230
30261
  userId;